Code Golf:用最少的代码行打印整个“12 Days of Christmas”歌曲

时间:2022-02-01 11:37:27

Print all 12 verses of the popular holiday song.

打印流行节日歌曲的所有12节经文。

By 12 verses I mean the repetition of each line as is sung in the song, ie

在12节经文中,我的意思是歌曲中所唱的每一行的重复,即

Verse One: On the first day of Christmas my true love gave to me a partridge in a pear tree.

第一节:在圣诞节的第一天,我的真爱给了我一棵梨树上的鹧..

Verse Two On the second day of Christmas my true love gave to me two turtle doves and a partridge in a pear tree.

第二节在圣诞节的第二天,我的真爱给了我两只斑鸠和一棵梨树上的鹧..

...

Verse N: On the nth day of Christmas my true love gave to me (Verse N-1 without the first line) (line added in verse N)

N:在圣诞节的第n天,我的真爱给了我(没有第一行的第N-1节)(第N行增加了一行)

45 个解决方案

#1


Common Lisp:

(mapc #'princ
      (reverse (maplist #'(lambda(l)
         (format nil 
            "On the ~:R day of Christmas my true love gave to me~%~{~a~%~}~%" 
                (length l) l)) 
    '("twelve drummers drumming,"
      "eleven pipers piping,"
      "ten lords a-leaping,"
      "nine ladies dancing,"
      "eight maids a-milking,"
      "seven swans a-swimming,"
      "six geese a-laying,"
      "five gold rings,"
      "four calling birds,"
      "three french hens,"
      "two turtle doves, and"
      "a partridge in a pear tree."))))

Edit:

Above is 412 characters if you take out the whitespace.

如果你取出空白,上面是412个字符。

This one:

(let ((g))
  (dotimes (i 12)
    (format t
        "On the ~:R day of Christmas my true love gave to me~%~{~R ~:*~
         ~[~;~;turtle doves and~;french hens,~;calling birds,~;gold rings,~
         ~;geese a-laying,~;swans a-swimming,~;maids a-milking,~
         ~;ladies dancing,~;lords a-leaping,~;pipers piping,~
         ~;drummers drumming,~]~%~}a partridge in a pear tree~2%"
        (1+ i) g)
    (push (+ i 2) g)))

is 344 characters if you take out whitespace and ~ quoted newlines in the format string:

如果你在格式字符串中取出空格和〜引用的换行符,则为344个字符:

(let((g))(dotimes(i 12)(format t"On the ~:R day of Christmas my true love gave to me~%~{~R ~:*~[~;~;turtle doves and~;french hens,~;calling birds,~;gold rings,~;geese a-laying,~;swans a-swimming,~;maids a-milking,~;ladies dancing,~;lords a-leaping,~;pipers piping,~;drummers drumming,~]~%~}a partridge in a pear tree~2%"(1+ i)g)(push(+ i 2)g)))

Edit:

It looks like the question has run its course, and the site is nagging me to accept an answer. As far as I can see, this one is the shortest. I'm a little afraid of what the site will do if I accept my own answer - probably award me a Narcissist or Masturbator badge.

看起来这个问题已经过去了,网站正在唠叨我接受一个答案。据我所知,这个是最短的。如果我接受自己的答案,我有点害怕网站会做什么 - 可能会给我一个自恋者或自慰者徽章。

You can't accept your own answers. Fair enough. I'll leave it open. Thanks to everyone who responded.

你无法接受自己的答案。很公平。我会把它打开。感谢大家的回应。

#2


Using F#:

#light
open System.Net; open System.Text.RegularExpressions
printf "%s" ((new WebClient()).DownloadString("http://www.textfiles.com/holiday/12-bugs")
    |> (fun x -> (new Regex("Lines: \d+\s+([\s\S]+)--")).Match(x).Groups.[1].Value))

Twelth day outputs:

第二天产出:

For the twelfth bug of Christmas, my manager said to me
     Tell them it's a feature
     Say it's not supported
     Change the documentation
     Blame it on the hardware
     Find a way around it
     Say they need an upgrade
     Reinstall the software
     Ask for a dump
     Run with the debugger
     Try to reproduce it
     Ask them how they did it and
     See if they can do it again.

#3


Not mine, but interesting...

不是我的,但很有意思......

This is a well-known example from http://en.wikipedia.org/wiki/Obfuscated_code (author: James O. Coplien):

这是http://en.wikipedia.org/wiki/Obfuscated_code(作者:James O. Coplien)的一个众所周知的例子:

#include <stdio.h>
main(t,_,a)char *a;{return!0<t?t<3?main(-79,-13,a+main(-87,1-_,
main(-86,0,a+1)+a)):1,t<_?main(t+1,_,a):3,main(-94,-27+t,a)&&t==2?_<13?
main(2,_+1,"%s %d %d\n"):9:16:t<0?t<-72?main(_,t,
"@n'+,#'/*{}w+/w#cdnr/+,{}r/*de}+,/*{*+,/w{%+,/w#q#n+,/#{l,+,/n{n+,/+#n+,/#\
;#q#n+,/+k#;*+,/'r :'d*'3,}{w+K w'K:'+}e#';dq#'l \
q#'+d'K#!/+k#;q#'r}eKK#}w'r}eKK{nl]'/#;#q#n'){)#}w'){){nl]'/+#n';d}rw' i;# \
){nl]!/n{n#'; r{#w'r nc{nl]'/#{l,+'K {rw' iK{;[{nl]'/w#q#n'wk nw' \
iwk{KK{nl]!/w{%'l##w#' i; :{nl]'/*{q#'ld;r'}{nlwb!/*de}'c \
;;{nl'-{}rw]'/+,}##'*}#nc,',#nw]'/+kd'+e}+;#'rdq#w! nr'/ ') }+}{rl#'{n' ')# \
}'+}##(!!/")
:t<-50?_==*a?putchar(31[a]):main(-65,_,a+1):main((*a=='/')+t,_,a+1)
  :0<t?main(2,2,"%s"):*a=='/'||main(0,main(-61,*a,
"!ek;dc i@bK'(q)-[w]*%n+r3#l,{}:\nuwloca-O;m .vpbks,fxntdCeghiry"),a+1);}

"Although unintelligible at first glance, it is a legal C program that when compiled and run will generate the 12 verses of The 12 Days of Christmas. It contains all the strings required for the poem in an encoded form inlined in the code. The code iterates through the 12 days displaying what it needs to."

“虽然乍一看是难以理解的,但它是一个合法的C程序,在编译和运行时将生成12个圣诞节的12节经文。它包含了代码中内联编码形式的诗所需的所有字符串。迭代12天,显示它需要的东西。“

It won't win golf though, it is about 830 bytes.

虽然它不会赢得高尔夫,但它大约是830个字节。

#4


class TrueLove: ITrueLove 
{
  List<IPresent> give(int day) 
  {
    List<IPresent> lovesLabourLost = new List<IPresent>();

    //if this was C++ could you replace this with a Figgy Duff Device?
    for (int i=1; i<=day; i++)
    {
      if(day > 1 && i<=2) {lovesLabourLost .Add(new TurtleDove());}
      if(day > 2 && i<=3) {lovesLabourLost .Add(new FrenchHen());}
      if(day > 3 && i<=4) {lovesLabourLost .Add(new CallingBird());}
      if(day > 4 && i<=5) {lovesLabourLost .Add(new GOLDRING());}
      if(day > 5 && i<=6) {lovesLabourLost .Add(new LayingGeese());}
      if(day > 6 && i<=7) {lovesLabourLost .Add(new SwimmingSwan());}
      if(day > 7 && i<=8) {lovesLabourLost .Add(new MilikingMaid());}
      if(day > 8 && i<=9) {lovesLabourLost .Add(new DancingLady());}
      if(day > 9 && i<=10) {lovesLabourLost .Add(new LeapingLord());}
      if(day > 10 && i<=11) {lovesLabourLost .Add(new PipingPiper());}
      if(day > 11 && i<=12) {lovesLabourLost .Add(new DrummingDrummer());}
    }

    return lovesLabourLost && (new PartridgeInPearTree());
  }
}

static class Me: IDemanding
{
  static ITrueLove myTrueLove = new TrueLove();

  static List<IPresent> myPresents = new List<IPresent>();

  static void demandPresents()
  {
    for (int i=1; i<=daysOfChristmas; i++)
    {
      List<IPresent> MOAR = myTrueLove.give(i);

      foreach (IPresent another in MOAR)
      {
        myPresents.Add(another);
      }
    }
  }
}

const int daysOfChristmas = 12;

Me.demandPresents();

#5


In the D programming language, using switch statement fall-through:

在D编程语言中,使用switch语句落实:

import std.stdio;

void main() {
    for(uint i = 1; i < 13; i++) {
        writeln("On the ", i, " day of Christmas, my true love gave to me:");
        switch(i) {
            case 12:
                writeln("twelve drummers drumming,");
            case 11:
                writeln("eleven pipers piping,");
            case 10:
                writeln("ten lords a-leaping,");
            case 9:
                writeln("nine ladies dancing,");
            case 8:
                writeln("eight maids a-milking,");
            case 7:
                writeln("seven swans a-swimming,");
            case 6:
                writeln("six geese a-laying,");
            case 5:
                writeln("five gold rings,");
            case 4:
                writeln("four calling birds,");
            case 3:
                writeln("three french hens,");
            case 2:
                writeln("two turtle doves, and");
            case 1:
                writeln("a partridge in a pear tree.\n");
        }
    }
}

#6


Bash:

wget -qO- http://tinyurl.com/a3xw8b

I used the output of frizzer.myopenid.com's CLisp implementation as a start.

我使用frizzer.myopenid.com的CLisp实现的输出作为开始。

#7


In C++ you'd

在C ++中你是

std::cout << boost::12_days_of_christmas;

#8


C#, 421 Characters

var t="";for(int i=0;i++<12;)Console.Write("On the {0}{1} day of Christmas, my true love gave to me: {2}\n",i,i<2?"st":i<3?"nd":i<4?"rd":"th",t="|a partridge in a pear tree.|two turtle doves, and |three french hens,|four calling birds,|five gold rings|six geese a-lay@seven swans a-swimm@eight maids a-milk@nine ladies danc@ten lords a-leap@eleven pipers pip@twelve drummers drumm@".Replace("@","ing,|").Split('|')[i]+t);

Spaced out version:

var t="";

for(int i = 0; i++ < 12;)
    Console.Write("On the {0}{1} day of Christmas, my true love gave to me: {2}\n",
            i,
            i < 2 ? "st" : i < 3 ? "nd" : i < 4 ? "rd" : "th",
            t="|a partridge in a pear tree.
               |two turtle doves, and 
               |three french hens,
               |four calling birds,
               |five gold rings
               |six geese a-lay
               @seven swans a-swimm
               @eight maids a-milk
               @nine ladies danc
               @ten lords a-leap
               @eleven pipers pip
               @twelve drummers drumm@"
            .Replace("@","ing,|")
            .Split('|')[i]+t);

#9


PHP: 375 characters

$v=split(":",":a partridge in a pear tree.\n:two turtle doves, and:three french hens:four calling birds:five gold rings:six geese a-lay:seven swans a-swimm:eigth maids a-milk:nine ladies danc:ten lords a-leap:eleven pipers pip:twelve drummers drumm");while($i<12){?>On the <?=date(jS,$i*86400)," day of Christmas my true love gave to me",$s=", ".$v[++$i].($i>5?'ing':'').$s;}

Edit: updated runnable version (377) characters

编辑:更新的可运行版本(377)字符

<?$v=split(":",":a partridge in a pear tree.\n:two turtle doves, and:three french hens:four calling birds:five gold rings:six geese a-lay:seven swans a-swimm:eigth maids a-milk:nine ladies danc:ten lords a-leap:eleven pipers pip:twelve drummers drumm");while($i<12){?>On the <?=date(jS,$i*86400)," day of Christmas my true love gave to me",$s=", ".$v[++$i].($i>5?'ing':'').$s;}

#10


Linq to objects, in 580 characters (without whitespace)

Linq到对象,580个字符(没有空格)

Console.WriteLine(Enumerable.Range(1, 13).SelectMany(day =>
    Enumerable.Repeat("\nOn the " + day + 
                      (day == 1 ? "st" : 
                      (day == 2 ? "nd" : 
                      (day == 3 ? "rd" : 
                      "th"))) + " day of Christmas my true love gave to me ", 1)
              .Concat((new []
                {
                    "twelve drummers drumming,",
                    "eleven pipers piping,",
                    "ten lords a-leaping,",
                    "nine ladies dancing,",
                    "eight maids a-milking,",
                    "seven swans a-swimming,",
                    "six geese a-laying,",
                    "five gold rings,",
                    "four calling birds,",
                    "three french hens,",
                    "two turtle doves, and",
                    "a partridge in a pear tree."
                }).Reverse().Take(day).Reverse()))
              .Aggregate((a, b) => a + "\n" + b));

#11


VB.Net - 530 Chars (no spaces), 634 (spaces)

VB.Net - 530个字符(无空格),634(空格)

Module ChristmasSong
    Sub Main()
        Dim i&, f$ : Dim d$() = {"first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth"}, g$() = {"a partridge in a pear tree.", "two turtle doves, and ", "three french hens, ", "four calling birds, ", "five gold rings, ", "six geese a-laying, ", "seven swans a-swimming, ", "eigth maids a-milking, ", "nine ladies dancing, ", "ten lords a-leaping, ", "eleven pipers piping, ", "twelve drummers drumming, "}
        For i = 0 To 11 : f = g(i) & f : Console.WriteLine("On the {0} day of Christmas, my true love gave to me {1}", d(i), f) : Next
    End Sub
End Module

#12


Perl.

use Lingua::EN::Numbers qw(num2en_ordinal);
print 'On the ', num2en_ordinal($_+1),' day of Christmas my true love gave to me, ', reverse(( split /\|/, "a partridge in a pear tree.\n|two turtle doves, and |three french hens, |four calling birds, |five gold rings, |six geese a-laying, |seven swans a-swimming, |eight maids a-milking, |nine ladies dancing, |ten lords a leaping, |eleven pipers piping, |twelve drummers drumming, ")[ 0 .. $_ ]) for 0 .. 11;

( 459 Chars )

(459个字符)

I wanted to make it a bit nicer and expressive, but this is a golf challenge.

我想让它变得更好,更具表现力,但这是一场高尔夫挑战。

This style violates proper coding standards somewhat. But that's golf for you.

这种风格有些违反了正确的编码标准。但那对你来说是高尔夫。

Lingua::EN::Number

Here's the less compact version with less sneaky tricks.

这是不太紧凑的版本,没有偷偷摸摸的技巧。

use Lingua::EN::Numbers qw(num2en_ordinal);
my @gifts = (
    'a partridge in a pear tree.',
    'two turtle doves, and ',
    'three french hens, ',
    'four calling birds, ',
    'five gold rings, ',
    'six geese a-laying, ',
    'seven swans a-swimming, ',
    'eight maids a-milking, ',
    'nine ladies dancing, ',
    'ten lords a leaping, ',
    'eleven pipers piping, ',
    'twelve drummers drumming, '
);
for my $verse_id ( 0 .. $#gifts ) {
    printf 'On the %s day of Christmas my true love gave to me, ', num2en_ordinal($verse_id +1);
    print reverse @verse[ 0 .. $verse_id ];
    print "\n";
}

#13


for d in range(12):print"On the %s day of Christmas, my true love gave to me\n\t%s\n"%("first|second|third|fourth|fifth|sixth|seventh|eighth|ninth|tenth|eleventh|twelfth".split("|")[d],"\n\t".join("twelve drummers drumming|eleven pipers piping|ten lords a-leaping|nine ladies dancing|eight maids a-milking|seven swans a-swimming|six geese a-laying|five gold rings|four calling birds|three french hens|two turtle doves and|a partridge in a pear tree.".split("|")[11-d:]))

Python, 422 chars

Python,422个字符

#14


LilyPond, 340 characters (shorter than Common Lisp)

'Tis the season! (And rather fitting, given that LilyPond is primarily used to typeset music... One can easily adapt this code to produce sheet music for the song in addition to just the lyrics.)

“这是赛季! (而且非常合适,因为LilyPond主要用于排版音乐......除了歌词之外,人们可以很容易地调整这段代码来为这首歌创作乐谱。)

Adapted from fizzer's solution.

改编自fizzer的解决方案。

#(map(lambda(x)(format #t"On the ~:R day of Christmas my true love gave to me~{ ~R~:*~[~;~;turtle doves and~;French hens,~;calling birds,~;gold rings,~;geese a-laying,~;swans a-swimming,~;maids a-milking,~;ladies dancing,~;lords a-leaping,~;pipers piping,~;drummers drumming,~]~} a partridge in a pear tree.
"x(iota(1- x)x -1)))(iota 12 1))

Usage: $ lilypond thisfile.ly

用法:$ lilypond thisfile.ly

This version, in 341 characters, matches fizzer's output exactly, but is three bytes shorter:

这个版本以341个字符完全匹配fizzer的输出,但缩短了三个字节:

#(map(lambda(x)(format #t"On the ~:R day of Christmas my true love gave to me~{
~R ~:*~[~;~;turtle doves and~;french hens,~;calling birds,~;gold rings,~;geese a-laying,~;swans a-swimming,~;maids a-milking,~;ladies dancing,~;lords a-leaping,~;pipers piping,~;drummers drumming,~]~}
a partridge in a pear tree

"x(iota(1- x)x -1)))(iota 12 1))

#15


Ruby. I think this is pretty concise (the hard work is all on one line):

红宝石。我认为这非常简洁(努力工作都在一条线上):

days = %w{First Second Third Fourth Fifth Sixth Seventh Eighth Ninth Tenth Eleventh Twelfth}

presents = [
    "twelve drummers drumming",
    "eleven pipers piping",
    "ten lords a leaping",
    "nine ladies dancing",
    "eight maids a-milking",
    "seven swans a-swimming",
    "six geese a-laying",
    "five gold rings",
    "four calling birds",
    "three french hens",
    "two turtle doves, and",
    "a partridge in a pear tree"
    ]

0.upto(11) { |i| 
    puts "On the #{days[i]} of Christmas my true love gave to me " + presents.last(i+1).join(", ")
}

#16


Using Template Toolkit

perl -MTemplate -e 'Template->new()->process("12dayxmas.tt")'

perl -MTemplate -e'Template-> new() - > process(“12dayxmas.tt”)'

12dayxmas.tt

[%
  list = [
    { day => 'first',    item => 'A partridge in a pear tree.'},
    { day => 'second',   item => 'Two turtle doves, and '},
    { day => 'third',    item => 'Three french hens, '},
    { day => 'fourth',   item => 'Four calling birds, '},
    { day => 'fifth',    item => 'Five gold rings, '},
    { day => 'sixth',    item => 'Six geese a-laying, '},
    { day => 'seventh',  item => 'Seven swans a-swimming, '},
    { day => 'eighth',   item => 'Eight maids a-milking, '},
    { day => 'nineth',   item => 'Nine ladies dancing, '},
    { day => 'tenth',    item => 'Ten lords a-leaping, '},
    { day => 'eleventh', item => 'Eleven pipers piping, '},
    { day => 'twelfth',  item => 'Twelve drummers drumming, '}
  ];
-%]
[%
  FOREACH list;
  present = item _ present;
-%]
On the [% day %] day of Christmas my true love gave me [% present %]

[% END %]

#17


Here's a PHP solution:

这是一个PHP解决方案:

$day = Array('first','second','third','fourth','fifth','sixth','seventh',
             'eighth','ninth','tenth','eleventh','twelfth');
$gifts = Array('Twelve drummers drumming,',
               'Eleven pipers piping,',
               'Ten lords a-leaping,',
               'Nine ladies dancing,',
               'Eight maids a-milking,',
               'Seven swans a-swimming,',
               'Six geese a-laying,',
               'FIVE GOLDEN RINGS,',
               'Four calling birds,',
               'Three French hens,',
               'Two turtle doves, and',
               'A partridge in a pear tree');

for ($i = 0; $i < 12; ++$i) {
    printf("On the $day[$i] of Christmas my true love gave to me\n" . 
         implode("\n", array_slice($gifts,-($i+1))) . "\n\n");
}

#18


h

In my made-up language where the command h prints "Hello, World!". Oh wait, you mean that's not what we're talking about?

在我的伪造语言中,命令h打印出“Hello,World!”。哦,等等,你的意思是,这不是我们所说的?

#19


Python (71+467 including whitespaces)

import sys
sys.path += ["TDOC.zip"]
import TDOC
TDOC.print_verse()

Where TDOC.zip (467 bytes) contains TDOC.py:

其中TDOC.zip(467字节)包含TDOC.py:

def print_verse(presents="""\
twelve drummers drumming,
eleven pipers piping,
ten lords a-leaping,
nine ladies dancing,
eigth maids a-milking,
seven swans a-swimming,
six geese a-laying,
five gold rings,
four calling birds,
three french hens,
two turtle doves, and
a partridge in a pear tree.""".split("\n")):
    if presents: 
        print_verse(presents[1:])

        number = presents[0].split(" ", 1)[0]
        print("On the %s day of Christmas my true love gave to me %s" % (
            dict(a="first", two="second", three="third", five="fifth").get(number, number+"th"),
            " ".join(presents)))

#20


C#:

string[] s = new string[]{
    "a partridge in a pear tree.",
    "two turtle doves, and ",
    "three french hens, ",
    "four calling birds, ",
    "five gold rings, ",
    "six geese a-laying, ",
    "seven swans a-swimming, ",
    "eight maids a-milking, ",
    "nine ladies dancing, ",
    "ten lords a-leaping, ",
    "eleven pipers piping, ",
    "twelve drummers drumming, "
    };
string t = "";
for (int x = 0; x < s.Length; x++) {
    t = s[x] + t;
    Console.Write("On the " 
      + (x + 1).ToString() 
      + (x == 0 ? "st" : (x == 1 ? "nd" : (x == 2 ? "rd" : "th"))) 
      + " day of christmas, my true love gave to me: " + t + "\n");
}

574 chars, not counting indenting. Adds some extra chars in getting the number extensions right. Can probably be improved on quite a bit, though.

574个字符,不计算缩进。添加一些额外的字符以使数字扩展正确。但是,可能会有相当大的改进。

#21


I can't beat the Lisp version, but it's still fun.

我无法击败Lisp版本,但它仍然很有趣。

The Delphi version:

Delphi版本:

procedure TheTwelfDaysOfChristmas(const AVerse: TStrings);
const 
  cPresentList : array[1..12] of string = (
    'a partridge in a pear tree',
    'two turtle doves, and ',
    'three french hens, ',
    'four calling birds, ',
    'five gold rings, ',
    'six geese a-laying, ',
    'seven swans a-swimming, ',
    'eigth maids a-milking, ',
    'nine ladies dancing, ',
    'ten lords a-leaping, ',
    'eleven pipers piping, ',
    'twelve drummers drumming, '
  );
  cTime : array[1..12] of string = (
    'first',
    'second',
    'third',
    'fourth',
    'fifth',
    'sixth',
    'seventh',
    'eighth',
    'nineth',
    'tenth',
    'eleventh',
    'twelfth'
  );
var
  present : string;
  i       : Integer;

begin
  present := '';
  for i := 1 to 12 do begin
    present := cPresentList[i] + present;
    AVerse.Add(Format('On the %s day of Christmas my true love gave me %s.',
      [cTime[i], present]));
  end;
end;

By the way, for all of you, Happy holidays and great programming in 2009.

顺便说一句,对于你们所有人来说,节日快乐和2009年的精彩节目。

#22


PHP

$g = array("a partridge in a pear tree.\n",
    "two turtle doves, and",
"three french hens,",
"four calling birds,",
"five gold rings,",
"six geese a-laying,",
"seven swans a-swimming,",
"eight maids a-milking,",
"nine ladies dancing,",
"ten lords a-leaping,",
"eleven pipers piping,",
"twelve drummers drumming,"
);
$d = array("first", "second", "third", "fourth", "fifth", "sixth",
 "seventh", "eighth", "nineth", "tenth", "eleventh", "twelfth");
foreach($d as $i=>$v){
    echo "On the $v day of Christmas my true love gave to me";
    for($j=$i;$j>=0;$j--) echo " ",$g[$j];
}

#23


26 bytes!..

As the URL implies, it may be considered.. cheating:

如URL所示,可能会被视为..作弊:

http://github.com/dbr/so_scripts/tree/master/golf_tdoc/cheating.bash

#24


Ruby

a=["and a partridge in a pear tree","turtle doves","French hens","calling birds","golden rings","geese a-laying","swans a-swimming","maids a-milking","ladies dancing","lords a-leaping","pipers piping","drummers drumming"]     
b=["","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve"]
c=["first","second","third","fourth","fifth","sixth","seventh","eighth","nineth","tenth","eleventh","twelfth"]
0.upto(11){|d|puts "On the "+c[d]+" day of Christmas, my true love gave to me:\n"+b[d]+" "+a[d]+",";(d-1).downto(0){|e| f=", ";f = "." if e==0;puts b[e]+" "+a[e]+f;}}

Total: 593bytes using UNIX LF.

总计:使用UNIX LF的593字节。

#25


C#

     string[] days = new string[] {"First", 
    "Second", "Third", "Fourth", "Fifth", "Sixth", 
    "Seventh", "Eighth", "Ninth", "Tenth", "Eleventh", "Twelfth"};

    string[] presents = new string[] {"a partridge in a pear tree.",
    "two turtle doves, and",
    "three french hens,", 
    "four calling birds,", 
    "five gold rings,", 
    "six geese a-laying,", 
    "seven swans a-swimming,", 
    "eigth maids a-milking,", 
    "nine ladies dancing,", 
    "ten lords a-leaping,", 
    "eleven pipers piping,", 
    "twelve drummers drumming,"};

     int cnt =0;
     foreach (string s in presents)
     {
           Console.WriteLine(string.Format("On the {0} day of Christmas my true love gave to me", days[cnt++]));
           foreach (string p in presents.Take(cnt).Reverse())
                Console.WriteLine(p);
           Console.WriteLine(System.Environment.NewLine);
     }

#26


Here's a Haskell version:

这是一个Haskell版本:

import Data.List
main=putStrLn$unlines$map(uncurry(\n->(++)("On the "++show n++case n of{1->"st";2->"nd";3->"rd";_->"th"}++" day of Christmas, my true love gave to me: ")))$zip[1..]$(\a->(drop 4$head a):tail a)$ map(intercalate", ".reverse)$tail$inits["and a partridge in a pair tree","two turtle doves","three french hens","four calling birds","five gold rings","six geese a-laying","seven swans a-swimming","eight maids a milking","nine ladies dancing","ten lords a-leaping","eleven pipers piping","twelve drummers drumming"]

It comes in at 527 characters. Since without good spacing it's rather incomprehensible, here's a more spread-out version:

它有527个字符。由于没有良好的间距,这是相当难以理解的,这是一个更加分散的版本:

import Data.List
main = putStrLn
       $ unlines
       $ map (uncurry (\n -> (++) ("On the " ++ show n ++ case n of { 1 -> "st"; 2 -> "nd"; 3 -> "rd"; _ -> "th"} ++ " day of Christmas, my true love gave to me: ")))
       $ zip [1..]
       $ (\a -> (drop 4 $ head a) : tail a)
       $ tail
       $ map (intercalate ", " . reverse)
             (inits ["and a partridge in a pair tree", "two turtle doves", "three french hens", "four calling birds", "five gold rings", "six geese a-laying", "seven swans a-swimming", "eight maids a milking", "nine ladies dancing", "ten lords a-leaping", "eleven pipers piping", "twelve drummers drumming"])

#27


Objective-C / Cocoa

Objective-C / Cocoa

NSArray *days = [NSArray arrayWithObjects:@"first", @"second", @"third", @"forth", 
                    @"fifth", @"six", @"seventh", @"eigth", 
                    @"ninth", @"tenth", @"eleventh", @"twelth", nil];

NSArray *gifts = [NSArray arrayWithObjects:
                    @"a partridge in a pear tree.\n\n",
                    @"two turtle doves, and\n",
                    @"three french hens,\n",
                    @"four calling birds,\n",                      
                    @"five gold rings,\n",
                    @"six geese a-laying,\n",
                    @"seven swans a-swimming,\n",
                    @"eigth maids a-milking,\n",                     
                    @"nine ladies dancing,\n",
                    @"ten lords a-leaping,\n",
                    @"eleven pipers piping,\n",    
                    @"twelve drummers drumming,\n",
                    nil];

NSMutableString *aggregator = [NSMutableString string];
for(int i = 0; i < 12; i++) {
    [aggregator insertString:[gifts objectAtIndex:i] atIndex:0];
    printf("on the %s day of xmas, my true love gave to me %s", [[days objectAtIndex:i] UTF8String], [aggregator UTF8String]);
}

#28


Another C#

var l="a partridge in a pear tree.|two turtle doves, and|three french hens,|four calling birds,|five gold rings,|six geese a-laying,|seven swans a-swimming,|eight maids a-milking,|nine ladies dancing,|ten lords a-leaping,|eleven pipers piping,|twelve drummers drumming,".Split('|');

for (int i = 1; i < 13; i++)
    Console.Write(
        "On the {0}{2} day of christmas\rmy true love gave to me \r{1}\r\r", 
            i, 
            string.Join("\r", l.Take(i).Reverse().ToArray()), 
            (i==1?"st":i==2?"nd":i==3?"rd":"th"));

Borrowed heavily from previous answers (hey, code reuse) while adding extra savings.

从以前的答案(嘿,代码重用)中大量借用,同时增加额外的节省。

481 characters once you take out unnecessary whitespace:

一旦你拿出不必要的空格,就会有481个字符:

var l="a partridge in a pear tree.|two turtle doves, and|three french hens,|four calling birds,|five gold rings,|six geese a-laying,|seven swans a-swimming,|eight maids a-milking,|nine ladies dancing,|ten lords a-leaping,|eleven pipers piping,|twelve drummers drumming,".Split('|');for(int i=1;i<13;i++)Console.Write("On the {0}{2} day of christmas, my true love gave to me \r{1}\r\r",i,String.Join("\r",l.Take(i).Reverse().ToArray()),(i==1?"st":i==2?"nd":i==3?"rd":"th")); 

#29


How about one line! This is in C#.

一行怎么样!这是在C#中。

Xmas(){Console.WriteLine("On the first day of Christmas,\r\nmy true love sent to me\r\nA partridge in a pear tree.\r\n\r\nOn the second day of Christmas,\r\nmy true love sent to me\r\nTwo turtle doves,\r\nAnd a partridge in a pear tree.\r\n\r\nOn the third day of Christmas,\r\nmy true love sent to me\r\nThree French hens,\r\nTwo turtle doves,\r\nAnd a partridge in a pear tree.\r\n\r\nOn the fourth day of Christmas,\r\nmy true love sent to me\r\nFour calling birds,\r\nThree French hens,\r\nTwo turtle doves,\r\nAnd a partridge in a pear tree.\r\n\r\nOn the fifth day of Christmas,\r\nmy true love sent to me\r\nFive golden rings,\r\nFour calling birds,\r\nThree French hens,\r\nTwo turtle doves,\r\nAnd a partridge in a pear tree.\r\n\r\nOn the sixth day of Christmas,\r\nmy true love sent to me\r\nSix geese a-laying,\r\nFive golden rings,\r\nFour calling birds,\r\nThree French hens,\r\nTwo turtle doves,\r\nAnd a partridge in a pear tree.\r\n\r\nOn the seventh day of Christmas,\r\nmy true love sent to me\r\nSeven swans a-swimming,\r\nSix geese a-laying,\r\nFive golden rings,\r\nFour calling birds,\r\nThree French hens,\r\nTwo turtle doves,\r\nAnd a partridge in a pear tree.\r\n\r\nOn the eighth day of Christmas,\r\nmy true, love sent to me\r\nEight maids a-milking,\r\nSeven swans a-swimming,\r\nSix geese a-laying,\r\nFive golden rings,\r\nFour calling birds,\r\nThree French hens,\r\nTwo turtle doves,\r\nAnd a partridge in a pear tree.\r\n\r\nOn the ninth day of Christmas,\r\nmy true love sent to me\r\nNine ladies dancing,\r\nEight maids a-milking,\r\nSeven swans a-swimming,\r\nSix geese a-laying,\r\nFive golden rings,\r\nFour calling birds,\r\nThree French hens,\r\nTwo turtle doves,\r\nAnd a partridge in a pear tree.\r\n\r\nOn the tenth day of Christmas,\r\nmy true love sent to me\r\nTen lords a-leaping,\r\nNine ladies dancing,\r\nEight maids a-milking,\r\nSeven swans a-swimming,\r\nSix geese a-laying,\r\nfive golden rings,\r\nFour calling birds,\r\nThree French hens,\r\nTwo turtle doves,\r\nAnd a partridge in a pear tree.\r\n\r\nOn the eleventh day of Christmas,\r\nmy true love sent to me\r\nEleven pipers piping,\r\nTen lords a-leaping,\r\nNine ladies dancing,\r\nEight maids a-milking,\r\nSeven swans a-swimming,\r\nSix geese a-laying\r\nFive golden rings,\r\nFour calling birds,\r\nThree French hens,\r\nTwo turtle doves,\r\nAnd a partridge in a pear tree.\r\n\r\nOn the twelfth day of Christmas,\r\nmy true love sent to me\r\nTwelve drummers drumming,\r\nEleven pipers piping,\r\nTen lords a-leaping,\r\nNine ladies dancing,\r\nEight maids a-milking,\r\nSeven swans a-swimming,\r\nSix geese a-laying,\r\nFive golden rings,\r\nFour calling birds,\r\nThree French hens,\r\nTwo turtle doves,\r\nAnd a partridge in a pear tree!");}

#30


Here's an erlang version (~586 chars):

这是一个erlang版本(约586个字符):

-module (xmas).
-export ([xmas/0]).
xmas() ->
    W = ["twelve drummers drumming, ",
    "eleven pipers piping, ",
    "ten lords a-leaping, ",
    "nine ladies dancing, ",
    "eight maids a-milking, ",
    "seven swans a-swimming, ",
    "six geese a-laying, ",
    "five gold rings, ",
    "four calling birds, ",
    "three french hens, ",
    "two turtle doves, and ",
    "a partridge in a pear tree."],
    io:format(lists:foldl(
    fun(X,Acc) -> Acc ++ X ++ "~n" end, "",
    ["On the " ++ day_str(Q) ++ 
    " day of Christmas, my true love gave me " ++ 
    lists:foldl(
        fun(X,Acc)-> Acc++X end,
        "", lists:nthtail(12-Q,W)) || 
        Q <- lists:seq(1,12)]),[]).
day_str(Q) ->
    case Q of
        1 -> "1st";
        2 -> "2nd";
        3 -> "3rd";
        N -> erlang:integer_to_list(N,10) ++ "th"
    end.

#1


Common Lisp:

(mapc #'princ
      (reverse (maplist #'(lambda(l)
         (format nil 
            "On the ~:R day of Christmas my true love gave to me~%~{~a~%~}~%" 
                (length l) l)) 
    '("twelve drummers drumming,"
      "eleven pipers piping,"
      "ten lords a-leaping,"
      "nine ladies dancing,"
      "eight maids a-milking,"
      "seven swans a-swimming,"
      "six geese a-laying,"
      "five gold rings,"
      "four calling birds,"
      "three french hens,"
      "two turtle doves, and"
      "a partridge in a pear tree."))))

Edit:

Above is 412 characters if you take out the whitespace.

如果你取出空白,上面是412个字符。

This one:

(let ((g))
  (dotimes (i 12)
    (format t
        "On the ~:R day of Christmas my true love gave to me~%~{~R ~:*~
         ~[~;~;turtle doves and~;french hens,~;calling birds,~;gold rings,~
         ~;geese a-laying,~;swans a-swimming,~;maids a-milking,~
         ~;ladies dancing,~;lords a-leaping,~;pipers piping,~
         ~;drummers drumming,~]~%~}a partridge in a pear tree~2%"
        (1+ i) g)
    (push (+ i 2) g)))

is 344 characters if you take out whitespace and ~ quoted newlines in the format string:

如果你在格式字符串中取出空格和〜引用的换行符,则为344个字符:

(let((g))(dotimes(i 12)(format t"On the ~:R day of Christmas my true love gave to me~%~{~R ~:*~[~;~;turtle doves and~;french hens,~;calling birds,~;gold rings,~;geese a-laying,~;swans a-swimming,~;maids a-milking,~;ladies dancing,~;lords a-leaping,~;pipers piping,~;drummers drumming,~]~%~}a partridge in a pear tree~2%"(1+ i)g)(push(+ i 2)g)))

Edit:

It looks like the question has run its course, and the site is nagging me to accept an answer. As far as I can see, this one is the shortest. I'm a little afraid of what the site will do if I accept my own answer - probably award me a Narcissist or Masturbator badge.

看起来这个问题已经过去了,网站正在唠叨我接受一个答案。据我所知,这个是最短的。如果我接受自己的答案,我有点害怕网站会做什么 - 可能会给我一个自恋者或自慰者徽章。

You can't accept your own answers. Fair enough. I'll leave it open. Thanks to everyone who responded.

你无法接受自己的答案。很公平。我会把它打开。感谢大家的回应。

#2


Using F#:

#light
open System.Net; open System.Text.RegularExpressions
printf "%s" ((new WebClient()).DownloadString("http://www.textfiles.com/holiday/12-bugs")
    |> (fun x -> (new Regex("Lines: \d+\s+([\s\S]+)--")).Match(x).Groups.[1].Value))

Twelth day outputs:

第二天产出:

For the twelfth bug of Christmas, my manager said to me
     Tell them it's a feature
     Say it's not supported
     Change the documentation
     Blame it on the hardware
     Find a way around it
     Say they need an upgrade
     Reinstall the software
     Ask for a dump
     Run with the debugger
     Try to reproduce it
     Ask them how they did it and
     See if they can do it again.

#3


Not mine, but interesting...

不是我的,但很有意思......

This is a well-known example from http://en.wikipedia.org/wiki/Obfuscated_code (author: James O. Coplien):

这是http://en.wikipedia.org/wiki/Obfuscated_code(作者:James O. Coplien)的一个众所周知的例子:

#include <stdio.h>
main(t,_,a)char *a;{return!0<t?t<3?main(-79,-13,a+main(-87,1-_,
main(-86,0,a+1)+a)):1,t<_?main(t+1,_,a):3,main(-94,-27+t,a)&&t==2?_<13?
main(2,_+1,"%s %d %d\n"):9:16:t<0?t<-72?main(_,t,
"@n'+,#'/*{}w+/w#cdnr/+,{}r/*de}+,/*{*+,/w{%+,/w#q#n+,/#{l,+,/n{n+,/+#n+,/#\
;#q#n+,/+k#;*+,/'r :'d*'3,}{w+K w'K:'+}e#';dq#'l \
q#'+d'K#!/+k#;q#'r}eKK#}w'r}eKK{nl]'/#;#q#n'){)#}w'){){nl]'/+#n';d}rw' i;# \
){nl]!/n{n#'; r{#w'r nc{nl]'/#{l,+'K {rw' iK{;[{nl]'/w#q#n'wk nw' \
iwk{KK{nl]!/w{%'l##w#' i; :{nl]'/*{q#'ld;r'}{nlwb!/*de}'c \
;;{nl'-{}rw]'/+,}##'*}#nc,',#nw]'/+kd'+e}+;#'rdq#w! nr'/ ') }+}{rl#'{n' ')# \
}'+}##(!!/")
:t<-50?_==*a?putchar(31[a]):main(-65,_,a+1):main((*a=='/')+t,_,a+1)
  :0<t?main(2,2,"%s"):*a=='/'||main(0,main(-61,*a,
"!ek;dc i@bK'(q)-[w]*%n+r3#l,{}:\nuwloca-O;m .vpbks,fxntdCeghiry"),a+1);}

"Although unintelligible at first glance, it is a legal C program that when compiled and run will generate the 12 verses of The 12 Days of Christmas. It contains all the strings required for the poem in an encoded form inlined in the code. The code iterates through the 12 days displaying what it needs to."

“虽然乍一看是难以理解的,但它是一个合法的C程序,在编译和运行时将生成12个圣诞节的12节经文。它包含了代码中内联编码形式的诗所需的所有字符串。迭代12天,显示它需要的东西。“

It won't win golf though, it is about 830 bytes.

虽然它不会赢得高尔夫,但它大约是830个字节。

#4


class TrueLove: ITrueLove 
{
  List<IPresent> give(int day) 
  {
    List<IPresent> lovesLabourLost = new List<IPresent>();

    //if this was C++ could you replace this with a Figgy Duff Device?
    for (int i=1; i<=day; i++)
    {
      if(day > 1 && i<=2) {lovesLabourLost .Add(new TurtleDove());}
      if(day > 2 && i<=3) {lovesLabourLost .Add(new FrenchHen());}
      if(day > 3 && i<=4) {lovesLabourLost .Add(new CallingBird());}
      if(day > 4 && i<=5) {lovesLabourLost .Add(new GOLDRING());}
      if(day > 5 && i<=6) {lovesLabourLost .Add(new LayingGeese());}
      if(day > 6 && i<=7) {lovesLabourLost .Add(new SwimmingSwan());}
      if(day > 7 && i<=8) {lovesLabourLost .Add(new MilikingMaid());}
      if(day > 8 && i<=9) {lovesLabourLost .Add(new DancingLady());}
      if(day > 9 && i<=10) {lovesLabourLost .Add(new LeapingLord());}
      if(day > 10 && i<=11) {lovesLabourLost .Add(new PipingPiper());}
      if(day > 11 && i<=12) {lovesLabourLost .Add(new DrummingDrummer());}
    }

    return lovesLabourLost && (new PartridgeInPearTree());
  }
}

static class Me: IDemanding
{
  static ITrueLove myTrueLove = new TrueLove();

  static List<IPresent> myPresents = new List<IPresent>();

  static void demandPresents()
  {
    for (int i=1; i<=daysOfChristmas; i++)
    {
      List<IPresent> MOAR = myTrueLove.give(i);

      foreach (IPresent another in MOAR)
      {
        myPresents.Add(another);
      }
    }
  }
}

const int daysOfChristmas = 12;

Me.demandPresents();

#5


In the D programming language, using switch statement fall-through:

在D编程语言中,使用switch语句落实:

import std.stdio;

void main() {
    for(uint i = 1; i < 13; i++) {
        writeln("On the ", i, " day of Christmas, my true love gave to me:");
        switch(i) {
            case 12:
                writeln("twelve drummers drumming,");
            case 11:
                writeln("eleven pipers piping,");
            case 10:
                writeln("ten lords a-leaping,");
            case 9:
                writeln("nine ladies dancing,");
            case 8:
                writeln("eight maids a-milking,");
            case 7:
                writeln("seven swans a-swimming,");
            case 6:
                writeln("six geese a-laying,");
            case 5:
                writeln("five gold rings,");
            case 4:
                writeln("four calling birds,");
            case 3:
                writeln("three french hens,");
            case 2:
                writeln("two turtle doves, and");
            case 1:
                writeln("a partridge in a pear tree.\n");
        }
    }
}

#6


Bash:

wget -qO- http://tinyurl.com/a3xw8b

I used the output of frizzer.myopenid.com's CLisp implementation as a start.

我使用frizzer.myopenid.com的CLisp实现的输出作为开始。

#7


In C++ you'd

在C ++中你是

std::cout << boost::12_days_of_christmas;

#8


C#, 421 Characters

var t="";for(int i=0;i++<12;)Console.Write("On the {0}{1} day of Christmas, my true love gave to me: {2}\n",i,i<2?"st":i<3?"nd":i<4?"rd":"th",t="|a partridge in a pear tree.|two turtle doves, and |three french hens,|four calling birds,|five gold rings|six geese a-lay@seven swans a-swimm@eight maids a-milk@nine ladies danc@ten lords a-leap@eleven pipers pip@twelve drummers drumm@".Replace("@","ing,|").Split('|')[i]+t);

Spaced out version:

var t="";

for(int i = 0; i++ < 12;)
    Console.Write("On the {0}{1} day of Christmas, my true love gave to me: {2}\n",
            i,
            i < 2 ? "st" : i < 3 ? "nd" : i < 4 ? "rd" : "th",
            t="|a partridge in a pear tree.
               |two turtle doves, and 
               |three french hens,
               |four calling birds,
               |five gold rings
               |six geese a-lay
               @seven swans a-swimm
               @eight maids a-milk
               @nine ladies danc
               @ten lords a-leap
               @eleven pipers pip
               @twelve drummers drumm@"
            .Replace("@","ing,|")
            .Split('|')[i]+t);

#9


PHP: 375 characters

$v=split(":",":a partridge in a pear tree.\n:two turtle doves, and:three french hens:four calling birds:five gold rings:six geese a-lay:seven swans a-swimm:eigth maids a-milk:nine ladies danc:ten lords a-leap:eleven pipers pip:twelve drummers drumm");while($i<12){?>On the <?=date(jS,$i*86400)," day of Christmas my true love gave to me",$s=", ".$v[++$i].($i>5?'ing':'').$s;}

Edit: updated runnable version (377) characters

编辑:更新的可运行版本(377)字符

<?$v=split(":",":a partridge in a pear tree.\n:two turtle doves, and:three french hens:four calling birds:five gold rings:six geese a-lay:seven swans a-swimm:eigth maids a-milk:nine ladies danc:ten lords a-leap:eleven pipers pip:twelve drummers drumm");while($i<12){?>On the <?=date(jS,$i*86400)," day of Christmas my true love gave to me",$s=", ".$v[++$i].($i>5?'ing':'').$s;}

#10


Linq to objects, in 580 characters (without whitespace)

Linq到对象,580个字符(没有空格)

Console.WriteLine(Enumerable.Range(1, 13).SelectMany(day =>
    Enumerable.Repeat("\nOn the " + day + 
                      (day == 1 ? "st" : 
                      (day == 2 ? "nd" : 
                      (day == 3 ? "rd" : 
                      "th"))) + " day of Christmas my true love gave to me ", 1)
              .Concat((new []
                {
                    "twelve drummers drumming,",
                    "eleven pipers piping,",
                    "ten lords a-leaping,",
                    "nine ladies dancing,",
                    "eight maids a-milking,",
                    "seven swans a-swimming,",
                    "six geese a-laying,",
                    "five gold rings,",
                    "four calling birds,",
                    "three french hens,",
                    "two turtle doves, and",
                    "a partridge in a pear tree."
                }).Reverse().Take(day).Reverse()))
              .Aggregate((a, b) => a + "\n" + b));

#11


VB.Net - 530 Chars (no spaces), 634 (spaces)

VB.Net - 530个字符(无空格),634(空格)

Module ChristmasSong
    Sub Main()
        Dim i&, f$ : Dim d$() = {"first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth"}, g$() = {"a partridge in a pear tree.", "two turtle doves, and ", "three french hens, ", "four calling birds, ", "five gold rings, ", "six geese a-laying, ", "seven swans a-swimming, ", "eigth maids a-milking, ", "nine ladies dancing, ", "ten lords a-leaping, ", "eleven pipers piping, ", "twelve drummers drumming, "}
        For i = 0 To 11 : f = g(i) & f : Console.WriteLine("On the {0} day of Christmas, my true love gave to me {1}", d(i), f) : Next
    End Sub
End Module

#12


Perl.

use Lingua::EN::Numbers qw(num2en_ordinal);
print 'On the ', num2en_ordinal($_+1),' day of Christmas my true love gave to me, ', reverse(( split /\|/, "a partridge in a pear tree.\n|two turtle doves, and |three french hens, |four calling birds, |five gold rings, |six geese a-laying, |seven swans a-swimming, |eight maids a-milking, |nine ladies dancing, |ten lords a leaping, |eleven pipers piping, |twelve drummers drumming, ")[ 0 .. $_ ]) for 0 .. 11;

( 459 Chars )

(459个字符)

I wanted to make it a bit nicer and expressive, but this is a golf challenge.

我想让它变得更好,更具表现力,但这是一场高尔夫挑战。

This style violates proper coding standards somewhat. But that's golf for you.

这种风格有些违反了正确的编码标准。但那对你来说是高尔夫。

Lingua::EN::Number

Here's the less compact version with less sneaky tricks.

这是不太紧凑的版本,没有偷偷摸摸的技巧。

use Lingua::EN::Numbers qw(num2en_ordinal);
my @gifts = (
    'a partridge in a pear tree.',
    'two turtle doves, and ',
    'three french hens, ',
    'four calling birds, ',
    'five gold rings, ',
    'six geese a-laying, ',
    'seven swans a-swimming, ',
    'eight maids a-milking, ',
    'nine ladies dancing, ',
    'ten lords a leaping, ',
    'eleven pipers piping, ',
    'twelve drummers drumming, '
);
for my $verse_id ( 0 .. $#gifts ) {
    printf 'On the %s day of Christmas my true love gave to me, ', num2en_ordinal($verse_id +1);
    print reverse @verse[ 0 .. $verse_id ];
    print "\n";
}

#13


for d in range(12):print"On the %s day of Christmas, my true love gave to me\n\t%s\n"%("first|second|third|fourth|fifth|sixth|seventh|eighth|ninth|tenth|eleventh|twelfth".split("|")[d],"\n\t".join("twelve drummers drumming|eleven pipers piping|ten lords a-leaping|nine ladies dancing|eight maids a-milking|seven swans a-swimming|six geese a-laying|five gold rings|four calling birds|three french hens|two turtle doves and|a partridge in a pear tree.".split("|")[11-d:]))

Python, 422 chars

Python,422个字符

#14


LilyPond, 340 characters (shorter than Common Lisp)

'Tis the season! (And rather fitting, given that LilyPond is primarily used to typeset music... One can easily adapt this code to produce sheet music for the song in addition to just the lyrics.)

“这是赛季! (而且非常合适,因为LilyPond主要用于排版音乐......除了歌词之外,人们可以很容易地调整这段代码来为这首歌创作乐谱。)

Adapted from fizzer's solution.

改编自fizzer的解决方案。

#(map(lambda(x)(format #t"On the ~:R day of Christmas my true love gave to me~{ ~R~:*~[~;~;turtle doves and~;French hens,~;calling birds,~;gold rings,~;geese a-laying,~;swans a-swimming,~;maids a-milking,~;ladies dancing,~;lords a-leaping,~;pipers piping,~;drummers drumming,~]~} a partridge in a pear tree.
"x(iota(1- x)x -1)))(iota 12 1))

Usage: $ lilypond thisfile.ly

用法:$ lilypond thisfile.ly

This version, in 341 characters, matches fizzer's output exactly, but is three bytes shorter:

这个版本以341个字符完全匹配fizzer的输出,但缩短了三个字节:

#(map(lambda(x)(format #t"On the ~:R day of Christmas my true love gave to me~{
~R ~:*~[~;~;turtle doves and~;french hens,~;calling birds,~;gold rings,~;geese a-laying,~;swans a-swimming,~;maids a-milking,~;ladies dancing,~;lords a-leaping,~;pipers piping,~;drummers drumming,~]~}
a partridge in a pear tree

"x(iota(1- x)x -1)))(iota 12 1))

#15


Ruby. I think this is pretty concise (the hard work is all on one line):

红宝石。我认为这非常简洁(努力工作都在一条线上):

days = %w{First Second Third Fourth Fifth Sixth Seventh Eighth Ninth Tenth Eleventh Twelfth}

presents = [
    "twelve drummers drumming",
    "eleven pipers piping",
    "ten lords a leaping",
    "nine ladies dancing",
    "eight maids a-milking",
    "seven swans a-swimming",
    "six geese a-laying",
    "five gold rings",
    "four calling birds",
    "three french hens",
    "two turtle doves, and",
    "a partridge in a pear tree"
    ]

0.upto(11) { |i| 
    puts "On the #{days[i]} of Christmas my true love gave to me " + presents.last(i+1).join(", ")
}

#16


Using Template Toolkit

perl -MTemplate -e 'Template->new()->process("12dayxmas.tt")'

perl -MTemplate -e'Template-> new() - > process(“12dayxmas.tt”)'

12dayxmas.tt

[%
  list = [
    { day => 'first',    item => 'A partridge in a pear tree.'},
    { day => 'second',   item => 'Two turtle doves, and '},
    { day => 'third',    item => 'Three french hens, '},
    { day => 'fourth',   item => 'Four calling birds, '},
    { day => 'fifth',    item => 'Five gold rings, '},
    { day => 'sixth',    item => 'Six geese a-laying, '},
    { day => 'seventh',  item => 'Seven swans a-swimming, '},
    { day => 'eighth',   item => 'Eight maids a-milking, '},
    { day => 'nineth',   item => 'Nine ladies dancing, '},
    { day => 'tenth',    item => 'Ten lords a-leaping, '},
    { day => 'eleventh', item => 'Eleven pipers piping, '},
    { day => 'twelfth',  item => 'Twelve drummers drumming, '}
  ];
-%]
[%
  FOREACH list;
  present = item _ present;
-%]
On the [% day %] day of Christmas my true love gave me [% present %]

[% END %]

#17


Here's a PHP solution:

这是一个PHP解决方案:

$day = Array('first','second','third','fourth','fifth','sixth','seventh',
             'eighth','ninth','tenth','eleventh','twelfth');
$gifts = Array('Twelve drummers drumming,',
               'Eleven pipers piping,',
               'Ten lords a-leaping,',
               'Nine ladies dancing,',
               'Eight maids a-milking,',
               'Seven swans a-swimming,',
               'Six geese a-laying,',
               'FIVE GOLDEN RINGS,',
               'Four calling birds,',
               'Three French hens,',
               'Two turtle doves, and',
               'A partridge in a pear tree');

for ($i = 0; $i < 12; ++$i) {
    printf("On the $day[$i] of Christmas my true love gave to me\n" . 
         implode("\n", array_slice($gifts,-($i+1))) . "\n\n");
}

#18


h

In my made-up language where the command h prints "Hello, World!". Oh wait, you mean that's not what we're talking about?

在我的伪造语言中,命令h打印出“Hello,World!”。哦,等等,你的意思是,这不是我们所说的?

#19


Python (71+467 including whitespaces)

import sys
sys.path += ["TDOC.zip"]
import TDOC
TDOC.print_verse()

Where TDOC.zip (467 bytes) contains TDOC.py:

其中TDOC.zip(467字节)包含TDOC.py:

def print_verse(presents="""\
twelve drummers drumming,
eleven pipers piping,
ten lords a-leaping,
nine ladies dancing,
eigth maids a-milking,
seven swans a-swimming,
six geese a-laying,
five gold rings,
four calling birds,
three french hens,
two turtle doves, and
a partridge in a pear tree.""".split("\n")):
    if presents: 
        print_verse(presents[1:])

        number = presents[0].split(" ", 1)[0]
        print("On the %s day of Christmas my true love gave to me %s" % (
            dict(a="first", two="second", three="third", five="fifth").get(number, number+"th"),
            " ".join(presents)))

#20


C#:

string[] s = new string[]{
    "a partridge in a pear tree.",
    "two turtle doves, and ",
    "three french hens, ",
    "four calling birds, ",
    "five gold rings, ",
    "six geese a-laying, ",
    "seven swans a-swimming, ",
    "eight maids a-milking, ",
    "nine ladies dancing, ",
    "ten lords a-leaping, ",
    "eleven pipers piping, ",
    "twelve drummers drumming, "
    };
string t = "";
for (int x = 0; x < s.Length; x++) {
    t = s[x] + t;
    Console.Write("On the " 
      + (x + 1).ToString() 
      + (x == 0 ? "st" : (x == 1 ? "nd" : (x == 2 ? "rd" : "th"))) 
      + " day of christmas, my true love gave to me: " + t + "\n");
}

574 chars, not counting indenting. Adds some extra chars in getting the number extensions right. Can probably be improved on quite a bit, though.

574个字符,不计算缩进。添加一些额外的字符以使数字扩展正确。但是,可能会有相当大的改进。

#21


I can't beat the Lisp version, but it's still fun.

我无法击败Lisp版本,但它仍然很有趣。

The Delphi version:

Delphi版本:

procedure TheTwelfDaysOfChristmas(const AVerse: TStrings);
const 
  cPresentList : array[1..12] of string = (
    'a partridge in a pear tree',
    'two turtle doves, and ',
    'three french hens, ',
    'four calling birds, ',
    'five gold rings, ',
    'six geese a-laying, ',
    'seven swans a-swimming, ',
    'eigth maids a-milking, ',
    'nine ladies dancing, ',
    'ten lords a-leaping, ',
    'eleven pipers piping, ',
    'twelve drummers drumming, '
  );
  cTime : array[1..12] of string = (
    'first',
    'second',
    'third',
    'fourth',
    'fifth',
    'sixth',
    'seventh',
    'eighth',
    'nineth',
    'tenth',
    'eleventh',
    'twelfth'
  );
var
  present : string;
  i       : Integer;

begin
  present := '';
  for i := 1 to 12 do begin
    present := cPresentList[i] + present;
    AVerse.Add(Format('On the %s day of Christmas my true love gave me %s.',
      [cTime[i], present]));
  end;
end;

By the way, for all of you, Happy holidays and great programming in 2009.

顺便说一句,对于你们所有人来说,节日快乐和2009年的精彩节目。

#22


PHP

$g = array("a partridge in a pear tree.\n",
    "two turtle doves, and",
"three french hens,",
"four calling birds,",
"five gold rings,",
"six geese a-laying,",
"seven swans a-swimming,",
"eight maids a-milking,",
"nine ladies dancing,",
"ten lords a-leaping,",
"eleven pipers piping,",
"twelve drummers drumming,"
);
$d = array("first", "second", "third", "fourth", "fifth", "sixth",
 "seventh", "eighth", "nineth", "tenth", "eleventh", "twelfth");
foreach($d as $i=>$v){
    echo "On the $v day of Christmas my true love gave to me";
    for($j=$i;$j>=0;$j--) echo " ",$g[$j];
}

#23


26 bytes!..

As the URL implies, it may be considered.. cheating:

如URL所示,可能会被视为..作弊:

http://github.com/dbr/so_scripts/tree/master/golf_tdoc/cheating.bash

#24


Ruby

a=["and a partridge in a pear tree","turtle doves","French hens","calling birds","golden rings","geese a-laying","swans a-swimming","maids a-milking","ladies dancing","lords a-leaping","pipers piping","drummers drumming"]     
b=["","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve"]
c=["first","second","third","fourth","fifth","sixth","seventh","eighth","nineth","tenth","eleventh","twelfth"]
0.upto(11){|d|puts "On the "+c[d]+" day of Christmas, my true love gave to me:\n"+b[d]+" "+a[d]+",";(d-1).downto(0){|e| f=", ";f = "." if e==0;puts b[e]+" "+a[e]+f;}}

Total: 593bytes using UNIX LF.

总计:使用UNIX LF的593字节。

#25


C#

     string[] days = new string[] {"First", 
    "Second", "Third", "Fourth", "Fifth", "Sixth", 
    "Seventh", "Eighth", "Ninth", "Tenth", "Eleventh", "Twelfth"};

    string[] presents = new string[] {"a partridge in a pear tree.",
    "two turtle doves, and",
    "three french hens,", 
    "four calling birds,", 
    "five gold rings,", 
    "six geese a-laying,", 
    "seven swans a-swimming,", 
    "eigth maids a-milking,", 
    "nine ladies dancing,", 
    "ten lords a-leaping,", 
    "eleven pipers piping,", 
    "twelve drummers drumming,"};

     int cnt =0;
     foreach (string s in presents)
     {
           Console.WriteLine(string.Format("On the {0} day of Christmas my true love gave to me", days[cnt++]));
           foreach (string p in presents.Take(cnt).Reverse())
                Console.WriteLine(p);
           Console.WriteLine(System.Environment.NewLine);
     }

#26


Here's a Haskell version:

这是一个Haskell版本:

import Data.List
main=putStrLn$unlines$map(uncurry(\n->(++)("On the "++show n++case n of{1->"st";2->"nd";3->"rd";_->"th"}++" day of Christmas, my true love gave to me: ")))$zip[1..]$(\a->(drop 4$head a):tail a)$ map(intercalate", ".reverse)$tail$inits["and a partridge in a pair tree","two turtle doves","three french hens","four calling birds","five gold rings","six geese a-laying","seven swans a-swimming","eight maids a milking","nine ladies dancing","ten lords a-leaping","eleven pipers piping","twelve drummers drumming"]

It comes in at 527 characters. Since without good spacing it's rather incomprehensible, here's a more spread-out version:

它有527个字符。由于没有良好的间距,这是相当难以理解的,这是一个更加分散的版本:

import Data.List
main = putStrLn
       $ unlines
       $ map (uncurry (\n -> (++) ("On the " ++ show n ++ case n of { 1 -> "st"; 2 -> "nd"; 3 -> "rd"; _ -> "th"} ++ " day of Christmas, my true love gave to me: ")))
       $ zip [1..]
       $ (\a -> (drop 4 $ head a) : tail a)
       $ tail
       $ map (intercalate ", " . reverse)
             (inits ["and a partridge in a pair tree", "two turtle doves", "three french hens", "four calling birds", "five gold rings", "six geese a-laying", "seven swans a-swimming", "eight maids a milking", "nine ladies dancing", "ten lords a-leaping", "eleven pipers piping", "twelve drummers drumming"])

#27


Objective-C / Cocoa

Objective-C / Cocoa

NSArray *days = [NSArray arrayWithObjects:@"first", @"second", @"third", @"forth", 
                    @"fifth", @"six", @"seventh", @"eigth", 
                    @"ninth", @"tenth", @"eleventh", @"twelth", nil];

NSArray *gifts = [NSArray arrayWithObjects:
                    @"a partridge in a pear tree.\n\n",
                    @"two turtle doves, and\n",
                    @"three french hens,\n",
                    @"four calling birds,\n",                      
                    @"five gold rings,\n",
                    @"six geese a-laying,\n",
                    @"seven swans a-swimming,\n",
                    @"eigth maids a-milking,\n",                     
                    @"nine ladies dancing,\n",
                    @"ten lords a-leaping,\n",
                    @"eleven pipers piping,\n",    
                    @"twelve drummers drumming,\n",
                    nil];

NSMutableString *aggregator = [NSMutableString string];
for(int i = 0; i < 12; i++) {
    [aggregator insertString:[gifts objectAtIndex:i] atIndex:0];
    printf("on the %s day of xmas, my true love gave to me %s", [[days objectAtIndex:i] UTF8String], [aggregator UTF8String]);
}

#28


Another C#

var l="a partridge in a pear tree.|two turtle doves, and|three french hens,|four calling birds,|five gold rings,|six geese a-laying,|seven swans a-swimming,|eight maids a-milking,|nine ladies dancing,|ten lords a-leaping,|eleven pipers piping,|twelve drummers drumming,".Split('|');

for (int i = 1; i < 13; i++)
    Console.Write(
        "On the {0}{2} day of christmas\rmy true love gave to me \r{1}\r\r", 
            i, 
            string.Join("\r", l.Take(i).Reverse().ToArray()), 
            (i==1?"st":i==2?"nd":i==3?"rd":"th"));

Borrowed heavily from previous answers (hey, code reuse) while adding extra savings.

从以前的答案(嘿,代码重用)中大量借用,同时增加额外的节省。

481 characters once you take out unnecessary whitespace:

一旦你拿出不必要的空格,就会有481个字符:

var l="a partridge in a pear tree.|two turtle doves, and|three french hens,|four calling birds,|five gold rings,|six geese a-laying,|seven swans a-swimming,|eight maids a-milking,|nine ladies dancing,|ten lords a-leaping,|eleven pipers piping,|twelve drummers drumming,".Split('|');for(int i=1;i<13;i++)Console.Write("On the {0}{2} day of christmas, my true love gave to me \r{1}\r\r",i,String.Join("\r",l.Take(i).Reverse().ToArray()),(i==1?"st":i==2?"nd":i==3?"rd":"th")); 

#29


How about one line! This is in C#.

一行怎么样!这是在C#中。

Xmas(){Console.WriteLine("On the first day of Christmas,\r\nmy true love sent to me\r\nA partridge in a pear tree.\r\n\r\nOn the second day of Christmas,\r\nmy true love sent to me\r\nTwo turtle doves,\r\nAnd a partridge in a pear tree.\r\n\r\nOn the third day of Christmas,\r\nmy true love sent to me\r\nThree French hens,\r\nTwo turtle doves,\r\nAnd a partridge in a pear tree.\r\n\r\nOn the fourth day of Christmas,\r\nmy true love sent to me\r\nFour calling birds,\r\nThree French hens,\r\nTwo turtle doves,\r\nAnd a partridge in a pear tree.\r\n\r\nOn the fifth day of Christmas,\r\nmy true love sent to me\r\nFive golden rings,\r\nFour calling birds,\r\nThree French hens,\r\nTwo turtle doves,\r\nAnd a partridge in a pear tree.\r\n\r\nOn the sixth day of Christmas,\r\nmy true love sent to me\r\nSix geese a-laying,\r\nFive golden rings,\r\nFour calling birds,\r\nThree French hens,\r\nTwo turtle doves,\r\nAnd a partridge in a pear tree.\r\n\r\nOn the seventh day of Christmas,\r\nmy true love sent to me\r\nSeven swans a-swimming,\r\nSix geese a-laying,\r\nFive golden rings,\r\nFour calling birds,\r\nThree French hens,\r\nTwo turtle doves,\r\nAnd a partridge in a pear tree.\r\n\r\nOn the eighth day of Christmas,\r\nmy true, love sent to me\r\nEight maids a-milking,\r\nSeven swans a-swimming,\r\nSix geese a-laying,\r\nFive golden rings,\r\nFour calling birds,\r\nThree French hens,\r\nTwo turtle doves,\r\nAnd a partridge in a pear tree.\r\n\r\nOn the ninth day of Christmas,\r\nmy true love sent to me\r\nNine ladies dancing,\r\nEight maids a-milking,\r\nSeven swans a-swimming,\r\nSix geese a-laying,\r\nFive golden rings,\r\nFour calling birds,\r\nThree French hens,\r\nTwo turtle doves,\r\nAnd a partridge in a pear tree.\r\n\r\nOn the tenth day of Christmas,\r\nmy true love sent to me\r\nTen lords a-leaping,\r\nNine ladies dancing,\r\nEight maids a-milking,\r\nSeven swans a-swimming,\r\nSix geese a-laying,\r\nfive golden rings,\r\nFour calling birds,\r\nThree French hens,\r\nTwo turtle doves,\r\nAnd a partridge in a pear tree.\r\n\r\nOn the eleventh day of Christmas,\r\nmy true love sent to me\r\nEleven pipers piping,\r\nTen lords a-leaping,\r\nNine ladies dancing,\r\nEight maids a-milking,\r\nSeven swans a-swimming,\r\nSix geese a-laying\r\nFive golden rings,\r\nFour calling birds,\r\nThree French hens,\r\nTwo turtle doves,\r\nAnd a partridge in a pear tree.\r\n\r\nOn the twelfth day of Christmas,\r\nmy true love sent to me\r\nTwelve drummers drumming,\r\nEleven pipers piping,\r\nTen lords a-leaping,\r\nNine ladies dancing,\r\nEight maids a-milking,\r\nSeven swans a-swimming,\r\nSix geese a-laying,\r\nFive golden rings,\r\nFour calling birds,\r\nThree French hens,\r\nTwo turtle doves,\r\nAnd a partridge in a pear tree!");}

#30


Here's an erlang version (~586 chars):

这是一个erlang版本(约586个字符):

-module (xmas).
-export ([xmas/0]).
xmas() ->
    W = ["twelve drummers drumming, ",
    "eleven pipers piping, ",
    "ten lords a-leaping, ",
    "nine ladies dancing, ",
    "eight maids a-milking, ",
    "seven swans a-swimming, ",
    "six geese a-laying, ",
    "five gold rings, ",
    "four calling birds, ",
    "three french hens, ",
    "two turtle doves, and ",
    "a partridge in a pear tree."],
    io:format(lists:foldl(
    fun(X,Acc) -> Acc ++ X ++ "~n" end, "",
    ["On the " ++ day_str(Q) ++ 
    " day of Christmas, my true love gave me " ++ 
    lists:foldl(
        fun(X,Acc)-> Acc++X end,
        "", lists:nthtail(12-Q,W)) || 
        Q <- lists:seq(1,12)]),[]).
day_str(Q) ->
    case Q of
        1 -> "1st";
        2 -> "2nd";
        3 -> "3rd";
        N -> erlang:integer_to_list(N,10) ++ "th"
    end.