25
\$\begingroup\$

I thought this would be a fun challenge for everyone and I'm curious to see the solutions people come up with.

Print the "12 Days Of Christmas" lyrics

On the first day of Christmas, 
my true love gave to me,
A partridge in a pear tree. 

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

...

On the twelfth day of Christmas,
My true love gave to me,
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.

Rules

  • You don't have to worry about capitalization; the entire text can be case insensitive
  • You can sensibly ignore any punctuation: hyphens can be spaces, and commas and periods can be ignored
  • There should be a blank line between each verse
  • You must ordinalize your numbers: "first day of Christmas", "Four calling birds", etc
\$\endgroup\$
11
  • \$\begingroup\$ Is that a "you can drop sentence capitals" or a "the whole text is case insensitive" kind of not worrying about capitalization? \$\endgroup\$
    – J B
    Dec 7, 2011 at 23:01
  • \$\begingroup\$ Also, in the line of ignoring punctuation, can we interchange punctuation for whitespace (and reciprocally)? \$\endgroup\$
    – J B
    Dec 7, 2011 at 23:03
  • \$\begingroup\$ JB, I hope my edit provides some more clarification for you \$\endgroup\$
    – macek
    Dec 7, 2011 at 23:34
  • \$\begingroup\$ Related : dezert-rose.com/humor/christmas/12daysreply.html \$\endgroup\$ Dec 8, 2011 at 4:31
  • 1
    \$\begingroup\$ @macek: better, but the latent side of my question was: can I print hyphens instead of spaces as well? \$\endgroup\$
    – J B
    Dec 8, 2011 at 12:10

26 Answers 26

28
\$\begingroup\$

Brainfuck - 2,974

I am rather proud of this one. That sounds like a pretty big number, but keep in mind, I did not use any external compression libraries, and none of the original text is in my program anywhere. None of the other submissions can say that. This is all hand coded. More naive text generators give over 39k for this text, so I would say this is a significant improvement.

>--[<->+++++]<---[>+>+>+>+>+<<<<<-]++++++++++>>[+++++>]<<<[+++++>]<<[+
++++>]<+++++>>++++[<++++++++>-]++++++++++++>+>+>>>>>>>>>>>>>+<<<<<<<<<
<<<<<<[<<<<++.-.->>>.<<++.--<<.<++.-->>>>>.>>>>>>>>>>>>>>[<<<<<<<<<<<<
<<<<++.>.<<<<++.-->>-.+<--.++>>.--<<.>>>>.>>>>>>>>>>>>>>-]<[<<<<<<<<<<
<<<<<<<<++.>>-.<<.>>>>-.+<<<<.-->>++.>++.--<<.>->>>.>>>>>>>>>>>>>>+<-]
<[<<<<<<<<<<<<<<++.<<<++.-->>+.->.--<<.>>>>.>>>>>>>>>>>>>+<-]<[<<<<<<<
<<<<<<<+.<+.>.->++.--<<-.>>>>.>>>>>>>>>>>>+<-]<[<<<<<<<<<<<<<<<++.-->+
.--.+.>>++.--<<.>>>>.>>>>>>>>>>>+<-]<[<<<<<<<<<<<+.<<<++.>>>>-.+<<<<.-
->>+.->+.--<<.>>>>.>>>>>>>>>>+<-]<[<<<<<<<<<<+.<<+.>>>+.-<+.--<<-.>>>>
.>>>>>>>>>+<-]<[<<<<<<<<<<<--.+++.---.>>++.--<<++.>>>>.>>>>>>>>+<-]<[<
<<<<<<<<<--.>++.-->>--.++<.++.--<<++.>>>>.>>>>>>>+<-]<[<<<<<<<++.<<.+.
->>--.<<<+.->>>>>.>>>>>>+<-]<[<<<<<<+.-<<<++.--.>>++.-.-<<+.->>>>>.>>>
>>+<-]<[<<<<<<<--.+++.->>.+.+.-->>.>>>>+<-]<<<<<<<<+.---.>>>>++.>.<<<+
+.<--.>>>>.<<<<<++.>++.>>.<<+.>>+.+.<--.<<--.>>>-.>>.<<<.>>.>.<<+.--.>
----.<<<<++++.>>>>>.<<<-.+++.>>+.<<<<.>>>>>.<<<<--.<----.>>>>.<<<<++++
.>>>>>.<<++.<.>>>.<<<--.<<.>>>>>.<<<<<-->+>>-->+>>>>>>>>>>>>>>>>>>>>>>
>>>>>>[<<<<<<<<<<<<<<<<<<<<<<<<<<<<<++.>.<<<<++.>>-.>>-.<<<<.->>>>>.<<
<<<.>>>--.>-.<<+..<<+.>>>.+.>>.<<<<<-.->>>-.>.<<..<+.>+.-<--.+>>>++>.>
>>>>>>>>>>>>>>>>>>>>>>>>>>-]<[<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<++.>>-.<<
.>>>>-.+<<<<.>>++.>>>.<<--.<<+.>>.<<<.-->>>++.+.>>.<<---.<<.>>.++<<.>.
-<--.+>>>>.>>>>>>>>>>>>>>>>>>>>>>>>>>-]<[<<<<<<<<<<<<<<<<<<<<<<<<<<<++
.<<<++.>>+.>>>.<<<--.+++.>--.<<<-.>>>+.>>.<<<<<---.>>>>>.<<<---.<<++++
.----.++>>>---.++<<+.>++.-<--.+>>>>.>>>>>>>>>>>>>>>>>>>>>>>>>-]<[<<<<<
<<<<<<<<<<<<<<<<<<<<<<+.<+.>.<<++.>>>>>.<<<--.<<----.+++.>.<+.>>>+.->>
.<<<<<-.---.>>++.<<++.>.>.-<--.+>>>>.>>>>>>>>>>>>>>>>>>>>>>>>-]<[<<<<<
<<<<<<<<<<<<<<<<<<<<<<<++.>+.--.+.>>++.>>.<<<.<<----.>+.<+++.>>>-.->>.
<<<<<---.++>>>>>.<<<.<.>-.-.<.>+++.-<--.+>>>>.>>>>>>>>>>>>>>>>>>>>>>>-
]<[<<<<<<<<<<<<<<<<<<<<<<<<+.<<<++.>>>>-.<<<<.>>+.>>>.<<.>+.<<<<----.>
>.>.>>.<<<<<.++>>>>>.<<.->.<<<+.>-..<.>+.-<--.+>>>>.>>>>>>>>>>>>>>>>>>
>>>>-]<[<<<<<<<<<<<<<<<<<<<<<<<+.<<+.>>>+.>.<<<<--.<++..>>>.-<<<.>>>>>
.<<<<<----.>>>>>.<<<-.<<.++>>>>+.--<<<++.>++.-<--.+>>>>.>>>>>>>>>>>>>>
>>>>>>>-]<[<<<<<<<<<<<<<<<<<<<<<<<<--.+++.>>>-.+<<<<++.>>>>>.<<<<--.>+
+.---.<<-.+.-->>++.>>>.<<.<<++.>.-<--.+>>+.->>.>>>>>>>>>>>>>>>>>>>>-]<
[<<<<<<<<<<<<<<<<<<<<<<<--.>++.>>--.++<.>>.<<<<<.--.>>---..<+++.>++.-<
--.>>>>.<<<<<+.>++.->>.<<<++.->>>+.->>.>>>>>>>>>>>>>>>>>>>-]<[<<<<<<<<
<<<<<<<<<<<<++.<<.>>--.<<<++..>>>>>.<<<<--.>>.<<<.>>+.<<--.>++.>>>>.<<
<<.<++.-->>.->+.->>.>>>>>>>>>>>>>>>>>>-]<[<<<<<<<<<<<<<<<<<<<++.>.<<++
.>>>.<<.>--.<--.++.<---.<<++.>>>>>.<<<<<-.>>+++.>>+.<<<<+.>>>-.>>.<<<<
<----.>>-.-<<+++.->>>->+>.>>>>>>>>>>>>>>>>>-]<[<<<<<<<<<<<<<<<<<<<<<--
.>>>>>.<<--.<<<.>>>++.++.--.<<+.<+++.>--.<+.>>>>>.<<<<++.>+.>>>.<<<<<-
---.>>>>>.<<<++.<<++++.----.>>>.>>.<<++.--.<<<++++..>>>>>.<<<<<-->->--
->>>>>>>>>>>>>>>>>>>-]<<<<<<<<<<<<<<<<<<<<<<..>>>>>>>->+[>+>>>>>>>>>>>
>>[>]+[<]<<<<<<<<<<<<<-]>[<+>-]<<]

Unfortunately, this is about 600 characters longer than its own output, but whatever. It keeps the characters c,h,m,r,w in an array, and uses that to print all text. Two arrays to the right of twelve spaces each keep track of which day we are on for the count, and for which items we can output. I may be able to optimize it a bit by reorganizing the memory map to bring the printing characters in between the two counting arrays to avoid such long chains of <<<<<<< and >>>>>>, but that would be a lot of work at this point. I could also probably choose some better seed characters with frequency analysis to minimize incrementing / decrementing, but whatever.

This does depend on 8-bit wrapping cells to work properly.

Ungolfed:

>--[<->+++++]<---

[>+>+>+>+>+<<<<<-]++++++++++
>>[+++++>]<<<[+++++>]<<[+++++>]<+++++>>
++++[<++++++++>-]
++++++++++++>+>+>>>>>>>>>>>>>+<<<<<<<<<<<<<<<
[ 
   <<<<++o.-n.->>>.<<++t.--<<h.<++e.-->>>>>.    
   >>>>>>>>>>>>>>
   12[<<<<<<<<<<<<<<<<++t.>w.<<<<++e.-->>-l.+<--f.++>>t.--<<h.>>>>.>>>>>>>>>>>>>>-]
   11<[<<<<<<<<<<<<<<<<<<++e.>>-l.<<e.>>>>-v.+<<<<e.-->>++n.>++t.--<<h.>->>>.>>>>>>>>>>>>>>+<-]
   10<[<<<<<<<<<<<<<<++t.<<<++e.-->>+n.->t.--<<h.>>>>.>>>>>>>>>>>>>+<-]
   9<[<<<<<<<<<<<< <<+n.<+i.>n.->++t.--<<-h.>>>> . >>>>>>>>>>>>+<-]
   8<[<<<<<<<<<<< <<<<++e.-->+i.--g.+h.>>++t.--<<h.>>>> . >>>>>>>>>>>+<-]
   7<[<<<<<<<<<< <+s.<<<++e.>>>>-v.+<<<<e.-->>+n.->+t.--<<h.>>>> . >>>>>>>>>>+<-]
   6<[<<<<<<<<< <+s.<<+i.>>>+x.-<+t.--<<-h.>>>> . >>>>>>>>>+<-]
   5<[<<<<<<<< <<<--f.+++i.---f.>>++t.--<<++h.>>>>. >>>>>>>>+<-]
   4<[<<<<<<< <<<--f.>++o.-->>--u.++<r.++t.--<<++h.>>>> . >>>>>>>+<-]
   3<[<<<<<< <++t.<<h.+i.->>--r.<<<+d.->>>>>.>>>>>>+<-]
   2<[<<<<<<+s.-<<<++e.--c.>>++o.-n.-<<+d.->>>>>.>>>>>+<-]
   1<[<<<<<<<--f.+++i.->>r.+s.+t.-->>.>>>>+<-]
   <<<<<<<<+d.---a.>>>>++y.>_.<<<++o.<--f.>>>>_.<<<<<++c.>++h.>>r.<<+i.>>+s.+t.
   <--m.<<--a.>>>-s.>>_.<<<m.>>y.>_.<<+t.--r.>----u.<<<<++++e.>>>>>_.
   <<<-l.+++o.>>+v.<<<<e.>>>>>_.   
   <<<<--g.<----a.>>>>v.<<<<++++e.>>>>>.
   <<++t.<o.>>>.
   <<<--m.<<e.>>>>>.
   <<<<<-->+>>-->+
   >>>>>>>>>>>>>>>>>>>>>>>>>>>>
   12[<<<<<<<<<<<<<<<<<<<<<<<<<<<<<++t.>w.<<<<++e.>>-l.>>-v.<<<<e.->>>>>.
   <<<<<d.>>>--r.>-u.<<+m.m.<<+e.>>>r.+s.>>.<<<<<-d.->>>-r.>u.<<m.m.<+i.>+n.-<--g.+>>>++>.
   >>>>>>>>>>>>>>>>>>>>>>>>>>>-]
   11<[<<<<<<<<<<<<<<<<<<<<<<<<<<< <<<<++e.>>-l.<<e.>>>>-v.+<<<<e.>>++n.>>>.
   <<--p.<<+i.>>p.<<<e.-->>>++r.+s.>>.<<---p.<<i.>>p.++<<i.>n.-<--g.+>>>>.>>>>>>>>>>>>>>>>>>>>>>>>>>-]
   10<[<<<<<<<<<<<<<<<<<<<<<<<<<< <++t.<<<++e.>>+n.>>> .<<<--
   .+++o.>--r.<<<-d.>>>+s.>>.<<<<<---a.>>>>>.<<<---l.<<++++e.----a.++>>>---p.++<<+
   i.>++n.-<--g.+>>>> .    >>>>>>>>>>>>>>>>>>>>>>>>>-]
   9< [<<<<<<<<<<<<<<<<<<<<<<<<< <<+n.<+i.>n.<<++e.>>>>> .<<<--l.<<----a.+++d.>
   i.<+e.>>>+s.->> .<<<<<-d.---a.>>++n.<<++c.>i.>n.-<--g.+>>>> . >>>>>>>>>>>>>>>>>>>>>>>>-]
   8< [<<<<<<<<<<<<<<<<<<<<<<<< <<<<++e.>+i.--g.+h.>>++t.>> .<<<m.<<----a.>+
   i.<+++d.>>>-s.->> .<<<<<---a.++>>>>> .<<<m.<i.>-l.-k.<i.>+++n.-<--g.+>>>> . >>>>>>>>>>>>>>>>>>>>>>>-]
   7< [<<<<<<<<<<<<<<<<<<<<<<< <+s.<<<++e.>>>>-v.<<<<e.>>+n.>>> .<<s.>+w.<<<<
   ----a.>>n.>s.>> .<<<<<a.++>>>>> .<<s.->w.<<<+i.>-m.m.<i.>+n.-<--g.+>>>>.  >>>>>>>>>>>>>>>>>>>>>>-]
   6< [<<<<<<<<<<<<<<<<<<<<<< <+s.<<+i.>>>+x.> .<<<<--g.<++e.e.>>>s.-<<<e.>>>>> 
   .<<<<<----a.>>>>> .<<<-l.<<a.++>>>>+y.--<<<++i.>++n.-<--g.+>>>> .  >>>>>>>>>>>>>>>>>>>>>-]
   5< [<<<<<<<<<<<<<<<<<<<<< <<<--f.+++i.>>>-v.+<<<<++e.>>>>> .<<<<--g.>++o.---
   l.<<-d.+e.-->>++n.>>> .<<r.<<++i.>n.-<--g.+>>+s.->> .   >>>>>>>>>>>>>>>>>>>>-]
   4< [<<<<<<<<<<<<<<<<<<<< <<<--f.>++o.>>--u.++<r.>> .<<<<<c.--a.>>---l.l.<+++
   i.>++n.-<--g.>>>> .<<<<<+b.>++i.->>r.<<<++d.->>>+s.->> .  >>>>>>>>>>>>>>>>>>>-]
   3< [<<<<<<<<<<<<<<<<<<< <++t.<<h.>>--r.<<<++e.e.>>>>> .<<<<--f.>>r.<<<e.>>+
   n.<<--c.>++h.>>>> .<<<<h.<++e.-->>n.->+s.->> .    >>>>>>>>>>>>>>>>>>-]
   2< [<<<<<<<<<<<<<<<<<<<++t.>w.<<++o.>>>.<<t.>--u.<--r.++t.<---l.<<++e.>>>>>.
   <<<<<-d.>>+++0.>>+v.<<<<+e.>>>-s.>>.<<<<<----a.>>-n.-<<+++d.->>>->+>.
   >>>>>>>>>>>>>>>>>-] 
   1<[<<<<<<<<<<<<<<<<<<<<<--a.>>>>>.<<p--.<<<a.>>>++r.++t.--r.<<+i.<+++d.>--g.<+
   e.>>>>>.<<<<++i.>+n.>>>.<<<<<----a.>>>>>.<<<++p.<<++++e.----a.>>>r.>>.<<++
   t.--r.<<<++++e..>>>>>.<<<<<-->->--->>>>>>>>>>>>>>>>>>>-]
   <<<<<<<<<<<<<<<<<<<<<<..>>>>>>>->+
   [>+>>>>>>>>>>>>>[>]+[<]<<<<<<<<<<<<<-]>[<+>-]<<
]
\$\endgroup\$
2
  • 1
    \$\begingroup\$ I'd tolerate inline comments on submissions of that size (uncounted for the golf score). +1'd anyway. \$\endgroup\$
    – J B
    Dec 17, 2011 at 18:51
  • \$\begingroup\$ Sure thing. Added ungolfed version. For the day numbers only one bit is set out of twelve, and after outputting it sets the next days bit. For items, the next to the last line sets n bits in a row high and all active get output. \$\endgroup\$
    – captncraig
    Dec 17, 2011 at 20:35
12
\$\begingroup\$

Common Lisp, 333 363

(dotimes(n 12)(format t"on-the-~:R-day-of-christmas
my-true-love-gave-to-me
~v*~@{~R-~A
~#[and-~]~}a-PARTRIDGE-IN-A-PEAR-TREE

"(1+ n)(- 22 n n)12'drummers-drumming 11'pipers-piping 10'lords-a-leaping 9'ladies-dancing 8'maids-a-milking 7'swans-a-swimming 6'geese-a-laying 5'golden-rings 4'calling-birds 3'french-hens 2'turtle-doves))

The builtin facilities to format ordinals are helpful, but most of the compression comes from being able to use the same argument list over and over, skipping over fewer and fewer arguments at each run.

As proven by coredump in the comments, the builtin facilities can still be put to good use for the cardinals.

\$\endgroup\$
4
  • \$\begingroup\$ Maybe you could compress a little more given that lines start with "twelve", "eleven", "ten", ... \$\endgroup\$
    – coredump
    Oct 24, 2014 at 15:09
  • \$\begingroup\$ Maybe it is. What's your suggestion? \$\endgroup\$
    – J B
    Oct 25, 2014 at 16:42
  • 2
    \$\begingroup\$ I first hoped that the remaining number of arguments could be used, but I read the spec and I can't do it. The shortes I have is 333 chars: (dotimes(n 12)(format t"on-the-~:R-day-of-christmas my-true-love-gave-to-me ~v*~@{~R-~A ~#[AND-~]~}A-PARTRIDGE-IN-A-PEAR-TREE "(1+ n)(- 22 n n)12'drummers-drumming 11'pipers-piping 10'lords-a-leaping 9'ladies-dancing 8'maids-a-milking 7'swans-a-swimming 6'geese-a-laying 5'golden-rings 4'calling-birds 3'french-hens 2'turtle-doves)) \$\endgroup\$
    – coredump
    Oct 29, 2014 at 7:38
  • \$\begingroup\$ Now we're talking. My dream would have been to share the skip counter with the ordinal, but I haven't found a short way to do that. \$\endgroup\$
    – J B
    Oct 29, 2014 at 10:27
10
\$\begingroup\$

Perl, 438 291 chars

Inspired by Jeff Burdges's use of DEFLATE compression, Ventero's compressed Ruby code and J B's use of Lingua::EN::Numbers, I managed to compress my entry down to 291 chars (well, bytes) including decompression code. Since the program contains some non-printable characters, I've provided it in MIME Base64 format:

dXNlIENvbXByZXNzOjpabGliO2V2YWwgdW5jb21wcmVzcyAneNolkMFqAkEMhu8+RVgELdaIXmXB
S2/FFyhF4k7cHTqTsclMZd++M3pJvo+QH5JiDJ9exkKrj/PqXOKV1bod77qj9b2UeGBZ7w/bpd9s
3rCDruf3uWtwS3qS/vfROy0xsho+oWbB3d+b19YsJHWGhIHp5eQ8GzqSoWkk/xxHH36a24OkuT38
K21kNm77ND81BceCWtlgoBAq4NWrM7gpyzDhxGKQi+bA6NIfG5K4/mg0d0kgTwwdvi67JHVeKKyX
l3acoxnSDYZJveVIBnGGrIUh1BQYqZacIDKc5Gvpt1vEk3wT3EmzejcyeIGqTApZmRftR7BH3B8W
/5Aze7In

To unencode the program, you can use the following helper Perl script:

use MIME::Base64;
print decode_base64 $_ while <>;

Save the output in a file named 12days.pl and run it with perl -M5.01 12days.pl. As noted, you need to have the Lingua::EN::Numbers module installed for the code to work.

In case you're wondering, the readable part of the code simply looks like this:

use Compress::Zlib;eval uncompress '...'

where the ... stands for 254 bytes of RFC 1950 compressed Perl code. Uncompressed, the code is 361 chars long and looks like this:

use Lingua'EN'Numbers"/e/";s==num2en(12-$i++)." "=e,y"." "for@n=qw=drummers.drumming pipers.piping lords.a.leaping ladies.dancing maids.a.milking swans.a.swimming geese.a.laying golden.rings calling.birds french.hens turtle.doves.and=;say"on the ".num2en_ordinal($_)." day of christmas my true love gave to me @n[$i--..@n]a partridge in a pear tree
"for 1..12

Writing this code was a weird kind of golfing exercise: it turns out the maximizing repetition and minimizing the number of distinct characters used are much more important than minimizing raw character count when the relevant metric is size after compression.

To squeeze out the last few chars, I wrote a simple program to try small variations of this code to find the one that compresses best. For compression, I used Ken Silverman's KZIP utility, which usually yield better compression rations (at the cost of speed) than standard Zlib even at the maximum compression settings. Of course, since KZIP only creates ZIP archives, I then had to extract the raw DEFLATE stream from the archive and wrap it in a RFC 1950 header and checksum. Here's the code I used for that:

use Compress::Zlib;
use 5.010;

@c = qw(e i n s);
@q = qw( " );
@p = qw( = @ ; , );
@n = ('\n',"\n");

$best = 999;

for$A(qw(e n .)){ for$B(@q){ for$C(@q,@p){ for$D(@p){ for$E(@q,@p){ for$F(qw(- _ . N E)){ for$G("-","-"eq$F?():$F){ for$H(@c){ for$I(@c,@p){ for$N(@n){ for$X(11,"\@$I"){ for$Y('$"','" "',$F=~/\w/?$F:()){ for$Z('".num2en_ordinal($_)."'){
    $M="Lingua'EN'Numbers";
    $code = q!use MB/A/B;sDDnum2en(12-$H++).YDe,yCFC Cfor@I=qwEdrummersFdrumming pipersFpiping lordsGaGleaping ladiesFdancing maidsGaGmilking swansGaGswimming geeseGaGlaying goldenFrings callingFbirds frenchFhens turtleFdovesFandE;say"on the Z day of christmas my true love gave to me @I[$H--..X]a partridge in a pear treeN"for 1..12!.$/;
    $code =~ s/[A-Z]/${$&}/g;

    open PL, ">12days.pl" and print PL $code and close PL or die $!;
    $output = `kzipmix-20091108-linux/kzip -b0 -y 12days.pl.zip 12days.pl`;
    ($len) = ($output =~ /KSflating\s+(\d\d\d)/) or die $output;

    open ZIP, "<12days.pl.zip" and $zip = join("", <ZIP>) and close ZIP or die $!;
    ($dfl) = ($zip =~ /12days\.pl(.{$len})/s) or die "Z $len: $code";

    $dfl = "x\xDA$dfl" . pack N, adler32($code);
    $dfl =~ s/\\(?=[\\'])|'/\\$&/g;

    next if $best <= length $dfl;
    $best = length $dfl;
    $bestcode = $code;
    warn "$A$B$C$D$E$F$G$H$I $X $Y $best: $bestcode\n";
    
    open PL, ">12days_best.pl" and print PL "use Compress::Zlib;eval uncompress '$dfl'" and close PL or die $!;

}}}}}}
    print STDERR "$A$B$C$D$E$F\r";
}}}}}}}

If this looks like a horrible kluge, it's because that's exactly what it is.


For historical interest, here's my original 438-char solution, which generates nicer output, including line breaks and punctuation:

y/_/ /,s/G/ing/for@l=qw(twelve_drummers_drummG eleven_pipers_pipG ten_lords-a-leapG nine_ladies_dancG eight_maids-a-milkG seven_swans-a-swimmG six_geese-a-layG five_golden_rGs four_callG_birds three_french_hens two_turtle_doves);s/e?t? .*/th/,s/vt/ft/for@n=@l;@n[9..11]=qw(third second first);say map("\u$_,\n","\nOn the $n[11-$_] day of Christmas,\nMy true love gave to me",@l[-$_..-1]),$_?"And a":A," partridge in a pear tree."for 0..11

Highlights of this version the pair of regexps s/e?t? .*/th/,s/vt/ft/, which construct the ordinals for 4 to 12 from the cardinals at the beginning of the gift lines.

This code can, of course, also be compressed using the Zlib trick described above, but it turns out that simply compressing the output is more efficient, yielding the following 338-byte program (in Base64 format, again):

dXNlIENvbXByZXNzOjpabGliO3NheSB1bmNvbXByZXNzICd42uWTwU7DMAyG730KP8DGOyA0bsCB
vYBp3MYicSo7W9e3xx3ijCIQDHZIUjn683+/k3ZPAjUSDKxWIeACZYC7qGw1o226hwWqHghSORKM
6FMtkGnT3cKEWpXDSMACCBOhQlWim+7jUKO+SGg5dT8XqAetiSD4nrmPBMDPvXywtllF18OgJH2E
SGJfcR+Ky2KL/b0roMeUWEZ4cXb7biQeGol4LZQUSECdyn4A0vjUBvnMXCcYiYy2uE24ONcvgdOR
pBF9lYDNKObwNnPOTnc5kYjH2JZotyogI4c1Ueb06myXH1S48eYeWbyKgclcJr2D/dnwtfXZ7km8
qOeUiXBysP/VEUrt//LurIGJXCdSWxeHu4JW1ZnS0Ph8XOKloIecSe39w/murYdvbRU+Qyc=

I also have a 312-byte gzip archive of the lyrics, constructed from the same DEFLATE stream. I suppose you could call it a "zcat script". :)

\$\endgroup\$
11
  • \$\begingroup\$ Looks like you can replace rings with rGs to save 2 chars \$\endgroup\$
    – macek
    Dec 8, 2011 at 1:17
  • \$\begingroup\$ @macek: In my original version I couldn't, because I was replacing G with ing,, but it turns out that adding the commas later is indeed shorter. Thanks! \$\endgroup\$ Dec 8, 2011 at 1:39
  • \$\begingroup\$ How do you avoid the 'modification of a read-only value' error? \$\endgroup\$ Dec 8, 2011 at 18:58
  • \$\begingroup\$ @JeffBurdges: In the original version? By assigning the strings to an array first. \$\endgroup\$ Dec 8, 2011 at 19:37
  • \$\begingroup\$ "Modification of a read-only value attempted at /opt/local/lib/perl5/5.12.3/Compress/Zlib.pm line 357." I avoided this issue by assigning to $_ in my update below. \$\endgroup\$ Dec 8, 2011 at 19:52
7
\$\begingroup\$

Python 2.7 (465)

for k in range(12):
 print'On the %s day of Christmas\nMy true love gave to me'%'first^second^third^fourth^fifth^sixth^seventh^eighth^ninth^tenth^eleventh^twelfth'.split('^')[k]
 print'\n'.join('Twelve drummers drumm*Eleven pipers pip*Ten lords-a-leap*Nine ladies danc*Eight maids-a-milk*Seven swans-a-swimm*Six geese-a-lay*Five golden rings^Four calling birds^Three french hens^Two turtle doves and^a partridge in a pear tree^'.replace('*','ing^').split('^')[11-k:])

However, I put the 'and' on the same line as the doves instead of the partridge.

\$\endgroup\$
0
7
\$\begingroup\$

JavaScript 570

This is my first time golfing. JavaScript 570

var l=["first","second","third","fourth","fifth","sixth","seventh","eigth","nineth","tenth","eleventh","twelth","Two turtle doves","Three french hens","Four calling birds","Five golden 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"];var b = "<br/>";for(var i=0;i<12;i++){var p="On the "+l[i]+"day of Christmas"+b+"My true love gave to me"+b;for(var x=i;x>0;x--)p+=l[13+x]+b;if(i>0)p+="and ";p+="a partridge in a pear tree"+b+b;document.write(p);}
\$\endgroup\$
6
\$\begingroup\$

Vim – 578 keystrokes

I decided to try and vim-golf this, since this is the kind of thing that can be vim-golfed.

Start by inserting the framework - the "X day of Christmas" line a total of 12 times (89 keystrokes):

                                         KS   TL   GT
12iOn the X day of Christmas,<Enter>     30   30   30
my true love gave to me,<Enter>          25   55   55
and a partridge in a pear tree.<Enter>   32   87   87
<Enter><Esc>                              2   89   89

Then, perform a series of macros that will insert the numbers 2 through 12 in the respective places they need to be for the lyrics (172 keystrokes):

                                      KS   TL   GT
42kqmO2<Esc>9/a<Enter>q10@m           17   17  106
dw                                     2   19  108
6jqm/2<Enter>O3<Esc>jq9@m             14   33  122
/3<Enter>qm/3<Enter>O4<Esc>jq8@m      16   49  138
/4<Enter>qm/4<Enter>O5<Esc>jq7@m      16   65  154
/5<Enter>qm/5<Enter>O6<Esc>jq6@m      16   81  170
/6<Enter>qm/6<Enter>O7<Esc>jq5@m      16   97  186
/7<Enter>qm/7<Enter>O8<Esc>jq4@m      16  113  202
/8<Enter>qm/8<Enter>O9<Esc>jq3@m      16  129  218
/9<Enter>qm/9<Enter>O10<Esc>jq2@m     17  146  235
/10<Enter>qm/10<Enter>O11<Esc>jq@m    18  164  253
?11<Enter>O12<Esc>                     8  172  261

The "dw" on the second line is to get rid of the first "and", because it doesn't go there.

Then, perform a series of substitutions for the number of things the true love gave (319 keystrokes):

                                       KS   TL   GT
:%s/12/twelve drummers drumming,/g     34   34  295
:%s/11/eleven pipers piping,/g         30   64  325
:%s/10/ten lords-a-leaping,/g          29   93  354
:%s/9/nine ladies dancing,/g           28  117  382
:%s/8/eight maids-a-milking,/g         30  147  412
:%s/7/seven swans-a-swimming,/g        31  178  443
:%s/6/six geese-a-laying,/g            27  205  366
:%s/5/five golden rings,/g             26  231  392
:%s/4/four calling birds,/g            27  268  419
:%s/3/three french hens,/g             26  294  445
:%s/2/two turtle doves,/g              25  319  470

And finally, replacing each occurrence of X with an ordinal number:

                         KS   TL   GT
/X<Enter>sfirst<Esc>     10   10  480
nssecond<Esc>             9   18  488
nsthird<Esc>              8   27  497
nsfourth<Esc>             9   36  506
nsfifth<Esc>              8   44  514
nssixth<Esc>              8   52  522
nsseventh<Esc>           10   62  532
nseighth<Esc>             9   71  541
nsninth<Esc>              8   79  549
nstenth<Esc>              8   87  557
nseleventh<Esc>          11   98  568
nstwelfth<Esc>           10  108  578

And we're done!


I'm sure there are other optimizations I missed, but I think that's pretty good myself.

\$\endgroup\$
2
  • \$\begingroup\$ Uh oh, I forgot the escapes. \$\endgroup\$
    – Joe Z.
    May 23, 2014 at 13:17
  • \$\begingroup\$ You can leave out the /g with the substitutions, like this: :%s/2/two turtle doves, \$\endgroup\$
    – 2xsaiko
    Jan 28, 2017 at 22:19
5
\$\begingroup\$

Ruby (474)

(0..11).each{|i|puts "On the #{"first^second^third^fourth^fifth^sixth^seventh^eighth^ninth^tenth^eleventh^twelfth".split("^")[i]} day of Christmas\nMy true love gave to me";puts "a partridge in a pear tree\n\n^two turtle doves and^three french hens^four calling birds^five golden 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 drumming".gsub('*','ing^').split('^')[0..i].reverse.join("\n")}

or in a more readable form (486):

(0..11).each do |i|
    puts "On the #{"first^second^third^fourth^fifth^sixth^seventh^eighth^ninth^tenth^eleventh^twelfth".split("^")[i]} day of Christmas\nMy true love gave to me"
    puts "a partridge in a pear tree\n\n^two turtle doves and^three french hens^four calling birds^five golden 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 drumming".gsub('*','ing^').split('^')[0..i].reverse.join("\n")
end

anybody got an idea how to circumvent the .reverse? i could't come up with a solution

\$\endgroup\$
5
  • 1
    \$\begingroup\$ I like your trick with * to represent "ing". You should be able to get it down to about 440 by: use 12.times instead of (0..11).each; do a single puts with two arguments instead of two puts with one argument; use %w() notation for the days-of-Christmas array. Finally, you can get rid of the reverse by reversing the list, adding an extra ^ to the end of the string, and then using [-i..-1] instead of [0..i]. \$\endgroup\$ Jan 5, 2014 at 18:41
  • 1
    \$\begingroup\$ couldn't you change "drumming" to "drumm*"? \$\endgroup\$ Oct 24, 2014 at 15:40
  • 1
    \$\begingroup\$ @WayneConrad just made a new version with your edits. I didn't get what you meant to "get rid of the reverse by reversing." 12.times{|i|puts"On the #{"First^Second^Third^Fourth^Fifth^Sixth^Seventh^Eighth^Ninth^Tenth^Eleventh^Twelfth".split("^")[i]} day of Christmas\nMy true love sent to me","A Partridge in a Pear Tree.\n\n^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*".gsub('*','ing,^').split('^')[0..i].reverse.join("\n")} \$\endgroup\$ May 5, 2022 at 21:31
  • \$\begingroup\$ @DaCuteRaccoon Huh. I don't get what I meant either. \$\endgroup\$ May 5, 2022 at 22:11
  • 1
    \$\begingroup\$ @WayneConrad Also sorry for the short message, I had to delete about 200 characters because I went over the limit. \$\endgroup\$ May 5, 2022 at 22:14
5
\$\begingroup\$

PowerShell, 440

-join('On the 1 day of Christmas
my true love gave to me
1a partridge in a pear tree

1first1second1third1fourth1fifth1sixth1seventh1eighth1ninth1tenth1eleventh1twelfth1Twelve drummers drumm7Eleven pipers pip7Ten lords-a-leap7Nine ladies danc7Eight maids-a-milk7Seven swans-a-swimm7Six geese-a-lay7Five golden rings
1Four calling birds
1Three french hens
1Two turtle doves
And '-replace7,'ing
1'-split1)[(26..15|%{0
29-$_
1
$_..26-le25
2})]

This prints the lyrics as given in the question with multiple lines per verse. We can save a few characters if that requirement isn't there.

\$\endgroup\$
2
  • \$\begingroup\$ +1 Holey crap. You got this working with line feeds as well as the "And" appearing on the last line. \$\endgroup\$ Dec 8, 2011 at 22:08
  • \$\begingroup\$ Well, printing a different text was never an option anyway, and the “And” in the last line uses the same trick like everyone else. Still, I wanted to preserve line breaks which the other solution does not (while being longer, too). \$\endgroup\$
    – Joey
    Dec 9, 2011 at 10:43
5
\$\begingroup\$

Perl, 500 485

@s=(first,second,third,fourth,fifth,sixth,seventh,eighth,ninth,tenth,eleventh,twelfth);
$;=ing;
@a=(
"Twelve drummers drumm$;",
"Eleven pipers pip$;",
"Ten lords-a-leap$;",
"Nine ladies danc$;",
"Eight maids-a-milk$;",
"Seven swans-a-swimm$;",
"Six geese-a-lay$;",
"Five golden r$;s",
"Four call$; birds",
"Three french hens",
"Two turtle doves\nAnd "
);
for(0..11){
print"\n\nOn the $s[$_] day of Christmas\nMy true love gave to me\n";
$"=$/;
print"@b";
unshift@b,pop@a;
print"A partridge in a pear tree"
}

This is my first attempt, and I am sure it could be made a lot shorter. The line breaks are for readability. It has three important arrays, one of which holds the name for each day @s, one of which lists off all of the gifts (except for the first one) @a, and one that lists off what gifts have already been given @b. The main mechanism is that each day, it prints @b and then transfers one additional gift from @a to @b.

Thanks to Andrew for 500->485

\$\endgroup\$
5
  • \$\begingroup\$ you can replace rings with r$1s to save 1 more char \$\endgroup\$
    – macek
    Dec 8, 2011 at 1:16
  • \$\begingroup\$ @macek I can't do that because perl will interpret the s as being part of the variable name, and the variable $is does not exist. (They are actually i's instead of ones, btw) \$\endgroup\$
    – PhiNotPi
    Dec 8, 2011 at 2:47
  • \$\begingroup\$ eigth -> eighth \$\endgroup\$ Dec 8, 2011 at 4:52
  • \$\begingroup\$ You could replace $i with, say, $; to get around that. Nobody ever uses $; for its intended purpose anyway. \$\endgroup\$ Dec 8, 2011 at 14:46
  • \$\begingroup\$ @IlmariKaronen I took your advice, but fixed a typo, so the character count stayed the same. \$\endgroup\$
    – PhiNotPi
    Dec 9, 2011 at 0:36
4
\$\begingroup\$

C (644)

Count does not include whitespace used for presentation.

#include <stdio.h>

void main() {
    char *e = "On the \0 day of Christmas my true love gave to me\0 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\n\n";
    printf("%sfirst%s%s%ssecond%s%s%sthird%s%s%sfourth%s%s%sfifth%s%s%ssixth%s%s%sseventh%s%s%seighth%s%s%sninth%s%s%stenth%s%s%seleventh%s%s%stwelfth%s%s",
           e, e+8, e+276, e, e+8, e+255, e, e+8, e+237, e, e+8, e+218, e, e+8, e+200, e, e+8, e+181, e, e+8, e+158, e, e+8, e+136, e, e+8, e+116, e, e+8, e+96, e, e+8, e+75, e, e+8, e+50);
}

Output is like:

On the first day of Christmas my true love gave to me A partridge in a pear tree

...

On the twelfth day of Christmas my true love gave to me 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
\$\endgroup\$
4
\$\begingroup\$

Powershell, 487 453

0..11 | % {
   'On the {0} day of christmas my true love gave to me {1}`n'-f
   (
        'first^second^third^fourth^fifth^sixth^seventh^eighth^ninth^tenth^eleventh^twelfth'.Split('^')[$_],
        (
            'a partridge in a pear tree^two turtle doves and^three french hens^four calling birds^five golden 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('^')[$_..0]-join' '
        )
    )
 }

Thank you to Daan for the idea of splitting a concatenated string.

I had originally included a switching statement to get the "and" on the partridge for all but the first verse. But, because the question absolves us of punctuation, we can just append the "and" to the doves.

This results in line feeds as follows:

On the first day of christmas my true love gave to me a partridge in a pear tree

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

On the third day of christmas my true love gave to me three french hens two turtle doves and a partridge in a pear tree
\$\endgroup\$
2
  • \$\begingroup\$ Twelfth, not twelveth. \$\endgroup\$
    – Joey Adams
    Dec 8, 2011 at 3:33
  • \$\begingroup\$ @Joey Adams - Thank you for correcting me and giving me one less character :-) \$\endgroup\$ Dec 8, 2011 at 9:14
4
\$\begingroup\$

Perl, 368 389 (no unicode/compression)

use Lingua::EN::Numbers"/n/";@s=qw(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);$_=$s[0];for$m(1..12){$n=num2en_ordinal$m;say"On the $n day of christmas
my true love gave to me
$_
";s/A/and a/;$_=num2en($m+1)." $s[$m]
$_"}

Harnesses Lingua::EN::Numbers, though I'm not 100% convinced it's a good idea when I see the module and its identifier names' lengths. Needs Perl 5.10 or later, run from the command line with a -E switch.

Edit: minor improvements: stop using an array, better use of $_, unneeded whitespace.

\$\endgroup\$
6
  • \$\begingroup\$ +1, Cool! Somebody might complain about using a non-standard module, but if we're allowing any language to be used (including special purpose ones like GolfScript), I don't see why "Perl + Lingua::EN::Numbers" wouldn't be a valid language for a solution. Writing an "Acme::12Days" module and submitting it to CPAN is probably cheating, though. :) \$\endgroup\$ Dec 8, 2011 at 14:57
  • \$\begingroup\$ @Ilmari Karonen when people complain, I usually rename the language to "CPAN". Doesn't happen often. \$\endgroup\$
    – J B
    Dec 8, 2011 at 16:15
  • 2
    \$\begingroup\$ Ilmari, Golfscript isn't a special-purpose language. \$\endgroup\$
    – Joey
    Dec 8, 2011 at 16:56
  • 2
    \$\begingroup\$ More like an "accidentally general"-purpose language :D \$\endgroup\$
    – J B
    Dec 8, 2011 at 17:03
  • 1
    \$\begingroup\$ Dear lord, why can't people golf their own code anymore? \$\endgroup\$
    – J B
    Dec 8, 2011 at 21:40
3
\$\begingroup\$

C# (528)

class P{static void Main(){for(int i=1;i<12;i++){Console.WriteLine("On the "+"^first^second^third^fourth^fifth^sixth^seventh^eighth^ninth^tenth^eleventh^twelfth".Split('^')[i]+" day of christmas my true love gave to me "+"a partridge in a pear tree^two turtle doves and^three french hens^four calling birds^five golden 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('^').Take(i).Aggregate("",(t,s)=>s+' '+t));}}}
\$\endgroup\$
2
\$\begingroup\$

PHP, 548

$n=explode('|','first|second|third|fourth|fifth|sixth|seventh|eighth|ninth|tenth|eleventh|twelfth');$w=explode('|','and a partridge in a pear tree.|two turtle doves|three french hens|four calling birds|five golden 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');foreach($n as $i=>$j)echo "on the $n[$i] day of christmas,\nmy true love sent to me\n".str_replace($i?'':'and ','',implode(",\n",array_reverse(array_slice($w,0,$i+1))))."\n\n";

Reduced length with compression, 502

eval(gzuncompress(base64_decode('eNpVkE1u3DAMhfc+BWEI8AzqDtJtg7QHCYKCsWiLrX4MUjPOAD58KE829UIyP5Hge8/lF/pYY/F0GvZhHGYWrbvSVLLfa2Dx+1yuUsM+82yn8kc76UbZbuIl2JW5FfWB4tdb3SjaxHB+dtv/OzB7QFhRqrBfCDi3klCgCtHFJgtU2xkJfLmRmg7jMAvlKUCgrIcmmDBGzgu8m0pDfCNYSvSUQQxr0woLkRLg94h3Yw/hoBtmNagbp9Tw4QMSsm84cfzXqNkiiOiZFDzmqTEzCbHI0RcJ12P6sAwrryTarqPR7JsgL9eUGj5+7MHymIsQTuHkzLeC45df7u+ZplCgLxlqIHD51fGbLb1DmWEKwloT6tilu2V0NVWWC6jlDLVAoq6/aJU/QmvEiU6Ofw/DzyNni3sYOT3S78euH1EE79Z6M1V0elQauY1t49Po+NuPs32Xvuv650+BSMT/')));
\$\endgroup\$
2
  • \$\begingroup\$ Not the kind of solution I like to read (yet another base-64/gzip, just great), but I really see no reason why you alone would deserve a negative answer score with that. Upvoted to bring some balance; whoever downvoted is requested to inform us of why. \$\endgroup\$
    – J B
    Dec 17, 2011 at 18:48
  • \$\begingroup\$ Many have provided a compressed solution so just for the fun of it I decided to put one also. But my original code is posted too, so I don't see what the problem is. Just ignore the gzipped one. I would also like to know why I was being downvoted. \$\endgroup\$
    – Vladimir
    Dec 18, 2011 at 14:53
2
\$\begingroup\$

Java, 2062

I know this was posted a while ago, but I thought I would try. I'm a student and still new to this but its seems to work.

public class TwelveDaysOfChristmas 
{

    public static void main(String[] args) 
    {
        String[] days = new String[12];
        days[0] = "and a partriage in a pear tree.";
        days[1] = "Two turtle doves, ";
        days[2] = "Three french hens, ";
        days[3] = "Four callings birds, ";
        days[4] = "Five diamond rings, ";
        days[5] = "Six geese a-laying, ";
        days[6] = "Seven swans a-swimming, ";
        days[7] = "Eight maids a-milking, ";
        days[8] = "Nine ladies dancing, ";
        days[9] = "Ten lords a-leaping, ";
        days[10] = "Eleven pipers piping, ";
        days[11] = "Twelve twelve drummers drumming, ";


        System.out.println(chorus(0));
        System.out.println("a partriage in a pear tree");

        for(int i = 1; i<days.length; i++)
        {
            System.out.println(chorus(i));

            for(int x = i; x>=0; x--)
            {
                System.out.println(days[x]);
            }
            System.out.println();
        }
    }

    public static String chorus(int line)
    {
        String chorus = "On the " + getLine(line) + " day of Christmas my true " +
                "love gave to me, ";

        return chorus;
    }

    public static String getLine(int line)
    {
        int num = line;
        String result = "first";
        switch (num)
        {
        case 1:  result = "second";
                 break;
        case 2:  result = "third";
                 break;
        case 3:  result = "fourth";
                 break;
        case 4:  result = "fifth";
                 break;
        case 5:  result = "sixth";
                 break;
        case 6:  result = "seventh";
                 break;
        case 7:  result = "eighth";
                 break;
        case 8:  result = "ninth";
                 break;
        case 9: result = "tenth";
                 break;
        case 10: result = "eleventh";
                 break;
        case 11: result = "twelfth";
                 break;
        }

        return result;
    }

}
\$\endgroup\$
2
  • \$\begingroup\$ Hi Gina, welcome to the site! \$\endgroup\$
    – Tynam
    Apr 19, 2012 at 10:16
  • 5
    \$\begingroup\$ Congrats on a first solution; works fine. The contest with code golf is 'shortest code possible', so it's standard on this site to do a few things you'd never do in normal code: cut variable and function names to one character, cut whitespace, and a few other things. (It's OK, and expected, to also include the full-length version as you did here to make the approach clearer.) Having done that, you can then ask yourself: "how can I make this shorter?" \$\endgroup\$
    – Tynam
    Apr 19, 2012 at 10:26
2
\$\begingroup\$

Swift, 577

import UIKit
let f=NSNumberFormatter()
f.numberStyle = .SpellOutStyle
for i in 0...11{
let w = split("first-second-third-four-fif-six-seven-eigh-nin-ten-eleven-twelf"){$0=="-"}[i]+(i<3 ?"":"th")
println("On the \(w) day of Christmas\nmy true love gave to me")
for m in reverse(0...i){
if m==0{break}
let v = split("turtle doves and*french hens*calling birds*golden rings*geese-a-lay*swans-a-swimm*maids-a-milk*ladies danc*lords-a-leap*pipers pip*drummers drumm"){$0=="*"}[m-1]+(m<5 ?"":"ing")
println("\(f.stringFromNumber(m+1)!) \(v)")}
println("a partridge in a pear tree.")}

You can paste this in a playground.

I tried moving the v into the print command and got:

Playground execution failed: <EXPR>:20:1: error: expression was too complex to be solved in reasonable time; consider breaking up the expression into distinct sub-expressions
\$\endgroup\$
2
\$\begingroup\$

///, 439 bytes

/|/\/\///^/on the |%/ day of christmas
my true love gave to me
|=/-a-|&/ing|*/even|+/th%|:/

^|A/el* pipers pip&
B|B/ten lords=leap&
C|C/nine ladies danc&
D|D/eight maids=milk&
E|E/s* swans=swimm&
F|F/six geese=lay&
G|G/five golden r&s
H|H/four call& birds
I|I/three french hens
J|J/two turtle doves
and K|K/a partridge in a pear tree/^first%K:second%J:+ird%I:four+H:fif+G:six+F:s*+E:eigh+D:nin+C:ten+B:el*+A:twelf+twelve drummers drumm&
A

Try it online!

If trailing newlines are allowed, you can save four bytes:

/|/\/\///^/on the |%/ day of christmas
my true love gave to me
|=/-a-|&/ing|*/even|+/th%|A/el* pipers pip&
B|B/ten lords=leap&
C|C/nine ladies danc&
D|D/eight maids=milk&
E|E/s* swans=swimm&
F|F/six geese=lay&
G|G/five golden r&s
H|H/four call& birds
I|I/three french hens
J|J/two turtle doves
and K|K/a partridge in a pear tree

/^first%K^second%J^+ird%I^four+H^fif+G^six+F^s*+E^eigh+D^nin+C^ten+B^el*+A^twelf+twelve drummers drumm&
A

Try it online!

Explanation

/// is a language where the only operation is a self-modifying substitution. In particular, the instruction /abc/xyz/ replaces all instances of abc with xyz in the rest of the source code, including other substitutions.. Any other characters are simply output to STDOUT.

While this is enough for Turing-completeness, golfing in /// generally consists of starting with the intended output and identifying repeated substrings that can be replaced with single-character shortcuts.

\ can be used as an escape character in patterns, replacements, and literal characters to mean a literal / or \.


The first instruction encountered is /|/\/\//. This means "replace all | with // in the rest of the program." This saves a byte for every subsequent substitution in the program.


After this, a set of replacements are made to compress the text itself:

  • on the becomes ^.
  • day of christmas \n my true love gave to me \n becomes %.
  • -a- becomes =.
  • ing becomes &.
  • even becomes *.
  • th% becomes +.
  • ^ preceded by two newlines (which appears in every verse but the first) becomes :.

Following this, we write the lyrics themselves. This is done using replacements A through K. Each letter replacement adds a line to the replacement after it. For example, K represents a partridge in a pear tree and J represents two turtle doves \n and K.

In this way, each verse of the song is composed of:

  • ^ or :
  • A string representing the correct ordinal (say, el*th)
  • %
  • A letter A through K that represents the correct lyrics.

However, because most of the ordinals end in th, we use the substitution th%+ to save some bytes.

\$\endgroup\$
1
\$\begingroup\$

Ruby 1.9.3, compressed, 321 characters

Since the code contains non-printable characters, I'll post a hexdump of the code instead:

0000000: 2363 6f64 696e 673a 6269 6e61 7279 0a72  #coding:binary.r
0000010: 6571 7569 7265 277a 6c69 6227 3b65 7661  equire'zlib';eva
0000020: 6c20 5a6c 6962 2e69 6e66 6c61 7465 2778  l Zlib.inflate'x
0000030: da2d 90db 6ac3 300c 86ef f714 a163 b042  .-..j.0......c.B
0000040: 15e8 5ea7 f442 8be5 58cc 8720 39cd 42db  ..^..B..X.. 9.B.
0000050: 3dfb e4a4 3792 f559 c7ff fcd5 574e a4f7  =...7..Y....WN..
0000060: 073f a6b9 eaa1 64a8 81e0 fdfe b17c 7a16  .?....d......|z.
0000070: ad9d d250 b2eb 6a60 719d 2fb3 d4d0 79f6  ...P..j`q./...y.
0000080: 6695 7f9b a51b 65f3 c463 3097 b905 7547  f.....e..c0...uG
0000090: f1f5 5717 8a56 71bc f0f5 090e 5728 1e86  ..W..Vq.....W(..
00000a0: 20ac 35a1 bea5 15aa cc04 b1dc 0846 3453   .5..........F4S
00000b0: 0b24 3a9c 6c87 5669 c0c9 9c12 89ee 0fce  .$:.l.Vi........
00000c0: e3ab 374c 3c35 6cae 411b 6b5d c429 2044  ..7L<5l.A.k].) D
00000d0: c28d d942 d61a 1d93 5563 1eb6 e2b6 2b24  ...B....Uc....+$
00000e0: e42d 3371 fc69 74bb 0474 c1dc a82e bc4f  .-3q.it..t.....O
00000f0: b233 6124 526a 4d71 6dc8 73db b444 67f9  .3a$RjMqm.s..Dg.
0000100: 6240 3761 60c0 182d 826f 934a 4d31 2102  b@7a`..-.o.JM1!.
0000110: 2f94 8700 81b2 91a5 4035 01a3 1d64 b7da  /[email protected]..
0000120: 1413 1661 42a9 c26e 24e0 6c33 2642 3141  ...aB..n$.l3&B1A
0000130: 888e 973f ee7b 385f 4fd3 f31f be35 9d6f  ...?.{8_O....5.o
0000140: 27                                       '

To create the actual code from the hexdump, put it in a file and run xxd -r hexdump > 12days.rb. Then executing ruby1.9.3 12.days.rb will run the code and print the lyrics. Note that this code requires Ruby 1.9.3 (because it uses Zlib.inflate) , so it won't work with Ruby 1.8.x, 1.9.1 and 1.9.2.

The uncompressed code is 425 characters long:

12.times{|i|puts"on-the-#{%w(first second third fourth fifth sixth seventh eighth ninth tenth eleventh twelfth)[i]}-day-of-christmas
my-true-love-gave-to-me",%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-golden-rings four-calling-birds three-french-hens two-turtle-doves-and a-partridge-in-a-pear-tree)[~i..-1],p}
\$\endgroup\$
1
\$\begingroup\$

Perl, 319/313

Idea : Uncompress and evaluate J B's Lingua::EN::Numbers solution.

First, paste this text block into the command perl -e 'use MIME::Base64; print decode_base64 $_ while <>;' >12days.pl. Next, run the command perl -M5.01 12days.pl.

dXNlIENvbXByZXNzOjpabGliOyRfPSd4nCWOwW7CMAyG730K
q8oBNIUOjq2QxmG3iT3AhJBpTBsRu12cgqpp776UXWx/v63/96QEH166Cev6/VjXx4kvFLWspCqb
N91/P1YHO2JM0buOrBeLdiSMNkUiSFNMgawb7qRwjSRtb3sShRZDyK724qNT6IbgSGzMSgYipewS
cM4M+kDRjPrwzIvA6N0isA+3hQM6T2odSvvEIT7XgXBcePRj/tfmtpCLE/PCzyEr68ac90a/Xk/N
dYiGV9vNZrtb/xjZy8Q7knP284LBcKM4l58CqVwnMAIOZxiu0PbRa2LUgmdIcaL8wZ2gw1zSAEyF
ORdlo9WhQnGA1RL4b70y/LJdb0rI+YZP+bD8Lf4A5ut+sic7ZXZhbCB1bmNvbXByZXNzJF87Cg==

The script itself takes the form use Compress::Zlib;$_='...';eval uncompress$_; where ... is J B's 368 char solution after being compressed with this command and escaping a '.

perl -M5.01 -e 'use Compress::Zlib; $_ .= <> while !eof; say compress($_);' <12days_JB.pl

Ilmari's script complains about modifying a read only value without the extra $_=...; characters, but presumably he'd make this 313. You could save several more bytes by tweaking the compression manually like Ilmari did before, maybe achieving 310 or so, but I didn't bother.


Perl, 376 (cheating off another submission) [my original submission]

First, create a perl script called 12days.pl containing :

use IO::Uncompress::Inflate qw(inflate);inflate\*DATA=>'-';
__DATA__

Next, pipe the output from any other submission into 12days.txt and execute the command :

perl -e 'use IO::Compress::Deflate qw(deflate); deflate "-" => "-";' <12days.txt >>12days.pl

Vola 12days.pl is around 376 bytes and prints the song. ;) Amusingly using rawinflate moves precisely six bytes from the data doc into the code starting from Ilmari's output.

I'd originally set about looking for a Huffman coding module directly, which isn't nearly so dishonest. Yet, sadly CPAN has no modules with English's letter entropy table, which is what you really want when compressing very short strings.

I found that fortune -m Days\ of\ Christmas does not work either, regrettably.

\$\endgroup\$
1
\$\begingroup\$

VALA, 584, 574

void main(){int i=0;string[] d={"first","second","thrid","fourth","fifth","sixth","seventh","eighth","ninth","tenth","eleventh","twelfth"};string[] p={"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","A"};while(i<12){stdout.printf("On the %s day of Christmas,\nmy true love gave to me,\n%s partridge in a pear tree.\n\n",d[i],string.joinv(",\n",p[11-i:12]));p[11]="And a";i++;}}

No more warning at compilation.

\$\endgroup\$
1
\$\begingroup\$

Java, 608

First post on Stack Exchange, second attempt at this problem.

class T{public static void main(String[]args){String Z=" partridge in a pear tree.\n";String[] B=(" day of Christmas,\nMy true love gave to me0first0second0third0fourth0fifth0sixth0seventh0eighth0ninth0tenth0eleventh0twelfth0A"+Z+"0Two turtle doves,0Three french hens,0Four calling birds,0Five golden rings,0Six geese-a-laying,0Seven swans-a-swimming,0Eight maids-a-milking,0Nine ladies dancing,0Ten lords-a-leaping,0Eleven pipers piping,0Twelve drummers drumming,").split("0");for(int i=1;i<13;i++){System.out.println("On the "+B[i]+B[0]);for(int j=i+12;j>12;j--)System.out.println(B[j]);B[13]="And a"+Z;}}}

Java is a little cumbersome for tasks like this, but using split helped reduce the String overhead.

\$\endgroup\$
3
  • \$\begingroup\$ @ceilingcat Nicely done. Shouldn't you post it as an answer? \$\endgroup\$
    – Ben I.
    Dec 26, 2020 at 4:06
  • \$\begingroup\$ I have more than enough imaginary internet points. \$\endgroup\$
    – ceilingcat
    Dec 26, 2020 at 4:53
  • \$\begingroup\$ 581 bytes \$\endgroup\$
    – ceilingcat
    Dec 26, 2020 at 5:05
1
\$\begingroup\$

Java, 630 bytes

public class code{public static void main(String[]a){int x=0;String[]l={"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,"};for(String d:new String[]{"First","Second","Third","Fourth","Fifth","Sixth","Seventh","Eighth","Ninth","Tenth","Eleventh","Twelfth"}){System.out.println("On the "+d+" day of Christmas\nMy true love sent to me");for(int i=0;i<=x;i++){System.out.println(l[x-i]);}x++;}}}

or as clean(ish) code:

public class code {
    public static void main(String[] a) {
        int x = 0;
        String[] l = new String[]{"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,"};
        for (String d : new String[]{"First", "Second", "Third", "Fourth", "Fifth", "Sixth", "Seventh", "Eighth", "Ninth", "Tenth", "Eleventh", "Twelfth"}) {
            System.out.println("On the " + d + " day of Christmas\nMy true love sent to me");
            for (int i = 0; i <= x; i++) {
                System.out.println(l[x - i]);
            }
            x++;
        }
    }
}

Example, including validation website: https://code.golf/12-days-of-christmas#java

I even got rank #13, I'd really love to get some feedback here. I'm pretty new to this, so would like to know some quick wins here for the Java edition!

\$\endgroup\$
2
1
\$\begingroup\$

JavaScript (Node.js), 566 bytes

for(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,","Eight Maids-a-Milking,","Nine Ladies Dancing,","Ten Lords-a-Leaping,","Eleven Pipers Piping,","Twelve Drummers Drumming,"],v=[],i=0;i<12;i++){for(l=["On the "+d[i]+" day of Christmas\nMy true love sent to me"],j=i+1,k=0;j-->0;)l[++k]=g[j];v[i]=l.join("\n")}console.log(v.join("\n\n"))

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Zsh -y, 383 bytes

for x y (first
two-turtle-doves second
three-french-hens third
`for a b (four call\ -birds
five golden-r\ s
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)()(<<<$a-$1ing$2\ ${${a%[et]}/%v/f}th) $b`)<<<"On the $x day of Christmas
my true love gave to me
$1a partridge in a pear tree
"&&1="$y
${1-and }"

Attempt This Online!

This may be the first time I've used Zsh's anonymous functions in golf. By combining it with the -y option, I can conveniently split $b into $1 and $2.

Makes use of some interesting symmetries:

  • all the gifts (starting with the fourth) contain ing
  • five -> fifth; twelve -> twelfth (that's a mini-etymology lesson for you)
  • nine -> ninth; eight -> eighth
\$\endgroup\$
0
\$\begingroup\$

Java - 1329 chars

class x{public static void main(String[] args){for(int i=1;i<=12;i++){System.out.print("On the ");switch(i){case 1:System.out.print("first");break;case 2:System.out.print("second");break;case 3:System.out.print("third");break;case 4:System.out.print("fourth");break;case 5:System.out.print("fifth");break;case 6:System.out.print("sixth");break;case 7:System.out.print("seventh");break;case 8:System.out.print("eighth");break;case 9:System.out.print("ninth");break;case 10:System.out.print("tenth");break;case 11:System.out.print("eleventh");break;case 12:System.out.print("twelfth");break;}System.out.println(" day of Christmas\nmy true love gave to me");switch(i){case 12:System.out.println("Twelve drummers drumming");case 11:System.out.println("Eleven pipers piping");case 10:System.out.println("Ten lords-a-leaping");case 9:System.out.println("Nine ladies dancing");case 8:System.out.println("Eight maids-a-milking");case 7:System.out.println("Seven swans-a-swimming");case 6:System.out.println("Six geese-a-laying");case 5:System.out.println("Five golden rings");case 4:System.out.println("Four calling birds");case 3:System.out.println("Three french hens");default:if(i>=2)System.out.print("Two turtle doves\nAnd a");else System.out.print("A");System.out.println(" partridge in a pear tree");break;}System.out.println();}}}

I'm too lazy to ungolf it, but it is here: http://ideone.com/MU9IcP.

\$\endgroup\$
0
\$\begingroup\$

Rust 525 chars

Messy:

fn main(){for i in 1..13{println!("On the {} day of Christmas,\nmy true love gave to me\n{}\n",["first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth"][i-1],["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."][(12-i)..12].join("\n"));}}

Formatted (haha rustfmt go brrr):

fn main() {
    for i in 1..13 {
        println!(
            "On the {} day of Christmas,\nmy true love gave to me\n{}\n",
            [
                "first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth",
                "ninth", "tenth", "eleventh", "twelfth"
            ][i - 1],
            [
                "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."
            ][(12 - i)..12]
                .join("\n")
        );
    }
}

I love how much this looks like the Python 2 and Ruby solutions (thanks for the inspiration). However, because the string split gives an iterator, I think the .split('^').collect::<Vec<str>>() I'd have to write would actually remove all the benefits of having ^-delimited strings instead of literal lists/arrays. (For the first substitution, I guess there's also .split('^').nth(i-1).unwrap(), but that's also a mouthful.)

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.