Question

Print all 12 verses of the popular holiday song.

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

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)

Was it helpful?

Solution

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.

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:

(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.

OTHER TIPS

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.

Not mine, but interesting...

This is a well-known example from http://en.wikipedia.org/wiki/Obfuscated_code (author: 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."

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

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();

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

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");
        }
    }
}

Bash:

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

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

In C++ you'd

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

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);

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

<?$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;}

Linq to objects, in 580 characters (without whitespace)

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));

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

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

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 )

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";
}
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

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.)

Adapted from fizzer's solution.

#(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

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

#(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))

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(", ")
}

Using Template Toolkit

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 %]

Here's a PHP solution:

$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");
}
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?

Python (71+467 including whitespaces)

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

Where TDOC.zip (467 bytes) contains 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)))

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.

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

The Delphi version:

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.

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];
}

26 bytes!..

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

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

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.

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);
     }

Here's a Haskell version:

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:

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"])

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]);
}

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:

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")); 

How about one line! This is in 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!");}

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

-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.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top