text:
12 Days of Christmas Lyrics
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

Is that a "you can drop sentence capitals" or a "the whole text is case insensitive" kind of not worrying about capitalization?

Also, in the line of ignoring punctuation, can we interchange punctuation for whitespace (and reciprocally)?

JB, I hope my edit provides some more clarification for you

Related : http://www.dezert-rose.com/humor/christmas/12daysreply.html

@macek: better, but the latent side of my question was: can I print hyphens instead of spaces as well?

J B, you can print hyphens, too, yes.

What about line breaks within the verses? Some solutions print the whole verse on a single line. Could I do the same? Or is whitespace even free-form as long as there is a blank line between verses and no blank line within verses?

Does "short" count bytes or characters? (e.g., Unicode could be used to encode roughly 4 chars [A-Z\-] of the poem in one char.)

Bruno, usually characters are counted. Also note that Unicode has non-characters which must not appear in interchange and plenty of holes in the code space. You can't just take four bytes and call it UCS-4. It will probably make most tools rightfully throw up. (Also four bytes won't fit, not even 7-bit per byte as Unicode is a 21-bit code.)

Unicode-compliant tools are supposed to cope with any unassigned code point, so you've got roughly 1000000 code points (with a little care). That's more than 27^4, hence four letters+space.

This is going to be my interview question tomorrow :) Love it

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..>>>>>.<<<<<-->->--->>>>>>>>>>>>>>>>>>>-]
   <<<<<<<<<<<<<<<<<<<<<<..>>>>>>>->+
   [>+>>>>>>>>>>>>>[>]+[<]<<<<<<<<<<<<<-]>[<+>-]<<
]

I'd tolerate inline comments on submissions of that size (uncounted for the golf score).  +1'd anyway.

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.

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.

Maybe you could compress a little more given that lines start with "twelve", "eleven", "ten", ...

Maybe it is. What's your suggestion?

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

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.

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

Looks like you can replace rings with rGs to save 2 chars

@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!

How do you avoid the 'modification of a read-only value' error?

@JeffBurdges: In the original version? By assigning the strings to an array first.

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

Yes yes, join eval compress dark side!  :)  Did you try starting with a Lingua::EN::Numbers solution?

@JeffBurdges: That's funny.  It works for me on both Perl 5.10.1 and 5.12.3.  What does perl -MCompress::Zlib -E 'say $Compress::Zlib::VERSION' say for you?  (Mine say 2.022 and 2.024 respectively.)

I'm 2.024 too, weird.

@JeffBurdges: I tried your advice to use Lingua::EN::Numbers and got it down to 297 bytes (without $_=, which would add three and save one for a total of 299).  I won't post it yet, though, since I think I can do better...

Yeah, I figured that'd improve things since I reached 313ish down thread without doing anything fancy.  $_=..;..$_ costs six, no?

@JeffBurdges: uncompress$_='...' should avoid the error, and costs only two chars over uncompress '...'.

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.

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

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.

Uh oh, I forgot the escapes.

You can leave out the /g with the substitutions, like this: :%s/2/two turtle doves,

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

you can replace rings with r$1s to save 1 more char

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

eigth -> eighth

You could replace $i with, say, $; to get around that.  Nobody ever uses $; for its intended purpose anyway.

@IlmariKaronen I took your advice, but fixed a typo, so the character count stayed the same.

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

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

couldn't you change "drumming" to "drumm*"?

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

@DaCuteRaccoon Huh.  I don't get what I meant either.

@WayneConrad Also sorry for the short message, I had to delete about 200 characters because I went over the limit.

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.

+1 Holey crap. You got this working with line feeds as well as the "And" appearing on the last line.

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

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

Twelfth, not twelveth.

@Joey Adams - Thank you for correcting me and giving me one less character :-)

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

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.

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

@Ilmari Karonen when people complain, I usually rename the language to "CPAN".  Doesn't happen often.

Ilmari, Golfscript isn't a special-purpose language.

More like an "accidentally general"-purpose language :D

Very nice one!  I'm stealing it.. and compressing it.  :P

Dear lord, why can't people golf their own code anymore?

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

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

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.

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.

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

}

Hi Gina, welcome to the site!

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?"

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

///, 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.

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.

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  /.......@5...d..
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}

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.

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.

@ceilingcat Nicely done.  Shouldn't you post it as an answer?

I have more than enough imaginary internet points.

581 bytes

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!

Welcome to Code Golf, nice first answer! You may want to check out our Tips for golfing in Java.

551 bytes

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

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!

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.

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


text:
Build a working chessboard
The challenge
Create a program that mimics a chessboard.
The datails
The chessboard must be surrounded by the labels of each row and column, being the columns labeled from 'a' to 'h' and the rows labeled from '1' to '8'. Also, place the default position for each chess piece (blacks are on the top). Each piece is represented by the first letter of his name:
King = K
Queen = Q
Rook = R
Bishop = B
Knight = N
Pawn = P

Also by his colour
W = White
B = Black

So any given piece is recognized by his name and colour. E.G: NB = Black Knight. Empty squares are represented by a hyphen (-).
The program must show the chess board with the pieces. Then it should ask the user to make a move with the message "Move". The program must read user input by console or equivalent. We don't care if the move is legal or not. The program must reprint the chess board with the piece moved, deleting any piece it was on that square. The move is represented origin square destination square. E.g:
2c 5d = Moves the piece in square 2c to square 5d

If the program detects there is not piece in the origin square or an invalid input, it must show the message "Invalid move" and ask again for another move. If the program detects the final square is occuped by another piece it must show the message "[Name of the moving piece] x [Name of the captured piece]". Eg:
PB x KW

The program is intended to run in a loop, so after each user input the program will ask again for another move. There is no exit clause for the loop.
Example of a initial chessboard and first user's input and program's output:
-   a   b   c   d   e   f   g   h   -

8   RB  NB  BB  QB  KB  BB  NB  RB  8

7   PB  PB  PB  PB  PB  PB  PB  PB  7

6   -   -   -   -   -   -   -   -   6

5   -   -   -   -   -   -   -   -   5

4   -   -   -   -   -   -   -   -   4

3   -   -   -   -   -   -   -   -   3

2   PW  PW  PW  PW  PW  PW  PW  PW  2

1   RW  NW  BW  QW  KW  BW  NW  RW  1

-   a   b   c   d   e   f   g   h   -

Move
2a 4a

-   a   b   c   d   e   f   g   h   -

8   RB  NB  BB  QB  KB  BB  NB  RB  8

7   PB  PB  PB  PB  PB  PB  PB  PB  7

6   -   -   -   -   -   -   -   -   6

5   -   -   -   -   -   -   -   -   5

4   PW  -   -   -   -   -   -   -   4

3   -   -   -   -   -   -   -   -   3

2   -   PW  PW  PW  PW  PW  PW  PW  2

1   RW  NW  BW  QW  KW  BW  NW  RW  1

-   a   b   c   d   e   f   g   h   -

Move

Conventionally white's pieces start on rows 1 and 2, not black's. 2. Is this intended to run in a loop? You haven't described how it takes input of the chessboard position. 3. If it is in a loop, how does it exit? 4. Is promotion impossible?

My bad. I had a internet problem when posting the question and it seems that the one I finally posted was the first version. I have added info and fixed the numbers in the chessboard. Promotion is impossible. The program only have to move the pieces reading user's input. I'm not sure I get what do you ask in 2. If you need more info, feel free to ask.

So after checkmate the user has to kill the program with Ctrl-C or equivalent? Meh. Looks like a pretty boring problem anyway if it doesn't have to check legality of moves, to be honest.

haha No prob :P When doing the question I was thinking checking the moves was adding a extra layer of difficult that people may consider excesive for making a program just for fun. Anyways, if the people wants to do it, I can change the question.

I'll just leave this here, not as a submission, but as a reminder of history: http://en.wikipedia.org/wiki/1K_ZX_Chess

Perl, 211 characters
y/W/B/for@8=@1=map$_.W,split//,RNBQKBNR;@b{$_.1..$_.9}=(@$_,/2/?PW:/7/?PB:"- ")x8for@r=reverse 1..8;$c=join"  ","",a..h;do{y/a-h\n/1-8/d;/ /;@b{$',$`}=@b{$`,19};say$c;say"$_ @b{$_.1..$_.8} $_"for@r;say$c}while<>

Nothing very unusual about this first attempt, except maybe the use of a do..while loop in golf.  Uses say, so you need to run this with perl -M5.01.  The input parsing is really klugy and fragile; in particular, excess whitespace will kill it.  On the other hand, you're not constrained to use 1-8 for rows and a-h for columns, either will do.  End the program with Ctrl-C or by ending the input (Ctrl-D in Unix).
I assumed I don't need to match the whitespace in the sample output exactly — I prefer a more compact board anyway.  (I did keep the board orientation, even though flipping it upside down would save me eight chars.)  A sample game session might look something like this:
  a  b  c  d  e  f  g  h
8 RB NB BB QB KB BB NB RB 8
7 PB PB PB PB PB PB PB PB 7
6 -  -  -  -  -  -  -  -  6
5 -  -  -  -  -  -  -  -  5
4 -  -  -  -  -  -  -  -  4
3 -  -  -  -  -  -  -  -  3
2 PW PW PW PW PW PW PW PW 2
1 RW NW BW QW KW BW NW RW 1
  a  b  c  d  e  f  g  h
2f 3f
  a  b  c  d  e  f  g  h
8 RB NB BB QB KB BB NB RB 8
7 PB PB PB PB PB PB PB PB 7
6 -  -  -  -  -  -  -  -  6
5 -  -  -  -  -  -  -  -  5
4 -  -  -  -  -  -  -  -  4
3 -  -  -  -  -  PW -  -  3
2 PW PW PW PW PW -  PW PW 2
1 RW NW BW QW KW BW NW RW 1
  a  b  c  d  e  f  g  h
7e 5e
  a  b  c  d  e  f  g  h
8 RB NB BB QB KB BB NB RB 8
7 PB PB PB PB -  PB PB PB 7
6 -  -  -  -  -  -  -  -  6
5 -  -  -  -  PB -  -  -  5
4 -  -  -  -  -  -  -  -  4
3 -  -  -  -  -  PW -  -  3
2 PW PW PW PW PW -  PW PW 2
1 RW NW BW QW KW BW NW RW 1
  a  b  c  d  e  f  g  h
2g 4g
  a  b  c  d  e  f  g  h
8 RB NB BB QB KB BB NB RB 8
7 PB PB PB PB -  PB PB PB 7
6 -  -  -  -  -  -  -  -  6
5 -  -  -  -  PB -  -  -  5
4 -  -  -  -  -  -  PW -  4
3 -  -  -  -  -  PW -  -  3
2 PW PW PW PW PW -  -  PW 2
1 RW NW BW QW KW BW NW RW 1
  a  b  c  d  e  f  g  h
8d 4h
  a  b  c  d  e  f  g  h
8 RB NB BB -  KB BB NB RB 8
7 PB PB PB PB -  PB PB PB 7
6 -  -  -  -  -  -  -  -  6
5 -  -  -  -  PB -  -  -  5
4 -  -  -  -  -  -  PW QB 4
3 -  -  -  -  -  PW -  -  3
2 PW PW PW PW PW -  -  PW 2
1 RW NW BW QW KW BW NW RW 1
  a  b  c  d  e  f  g  h
^C

You don't print out "Move" to prompt for a move. Do you print out the PB x KW for a capture either? I did not see anything in your code that looks like it would do that.

@Kevin: You're right, I missed those requirements. I'm going to have to rethink the design a bit.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Good rational approximations of pi
Write a program that prints out all the good rational approximations of pi with denominator < 1000000, in increasing denominator order.  a/b is a "good rational approximation" of pi if it is closer to pi than any other rational with denominator no bigger than b.
The output should have 167 lines total, and start and end like this:
3/1
13/4
16/5
19/6
22/7
179/57
...
833719/265381
1146408/364913
3126535/995207

Shortest program wins.

Does it have to be the string a/b or is a b also allowed?

Golfscript, 71 70 69 chars
2\!:^2^..292^15.2/3]{(.)2/.9>+{\+.((}*;.}do;;]-1%{^0@{2$*+\}/"/"\n}/;

(Assumes that you don't pass it anything on stdin)
I don't want to hear any more whinging by people who don't have built-in constants for pi. I don't even have floating point numbers!
See http://en.wikipedia.org/wiki/Continued_fraction#Best_rational_approximations for the background.
# No input, so the stack contains ""
2\!:^2^..292^15.2/3]
# ^ is used to store 1 because that saves a char by allowing the elimination of whitespace
# Otherwise straightforward: stack now contains [2 1 2 1 1 1 292 1 15 7 3]
# Pi as a continued fraction is 3+1/(7+1/(15+1/(...)))
# If you reverse the array now on the stack you get the first 10 continuants followed by 2
# (rather than 3)
# That's a little hack to avoid passing the denominator 1000000

{
    # Stack holds: ... [c_n c_{n-1} ... c_0]
    (.)2/.9>+
    # Stack holds ... [c_{n-1} ... c_0] c_n (1+c_n)/2+((1+c_n)/2 > 9 ? 1 : 0)
    # (1+c_n)/2 > 9 is an ad-hoc approximation of the "half rule"
    # which works in this case but not in general
    # Let k = (1+c_n)/2+((1+c_n)/2 > 9 ? 1 : 0)
    # We execute the next block k times
    {
        # ... [c_{n-1} ... c_0] z
        \+.((
        # ... [z c_{n-1} ... c_0] [c_{n-1} ... c_0] z-1
    }*
    # So we now have ... [c_n c_{n-1} ... c_0] [(c_n)-1 c_{n-1} ... c_0] ...
    #                    [(c_n)-k+1 c_{n-1} ... c_0] [c_{n-1} ... c_0] c_n-k
    ;
    # Go round the loop until the array runs out
    .
}do

# Stack now contains all the solutions as CFs in reverse order, plus two surplus:
# [2 1 2 1 1 1 292 1 15 7 3] [1 2 1 1 1 292 1 15 7 3] ... [6 3] [5 3] [4 3] [3] [2] []
# Ditch the two surplus ones, bundle everything up in an array, and reverse it
;;]-1%

# For each CF...
{
    # Stack holds ... [(c_n)-j c_{n-1} ... c_0]
    # We now need to convert the CF into a rational in canonical form
    # We unwind from the inside out starting with (c_n)-j + 1/infinity,
    # representing infinity as 1/0
    ^0@
    # ... 1 0 [c_n-j c_{n-1} ... c_0]
    # Loop over the terms of the CF
    {
        # ... numerator denominator term-of-CF
        2$*+\
        # ... (term-of-CF * numerator + denominator) numerator
    }/

    # Presentation
    "/"\n
    # ... numerator "/" denominator newline
}/

# Pop that final newline to avoid a trailing blank line which isn't in the spec
;

Well, technically GolfScript has both floating point numbers and constant for PI. It's called "#{Math.PI}".

@GlitchMr, in what way is a string a floating point number?

I'd really like to see this unrolled with comments.

Amazing. The very first line 2\!:^2^..292^15.2/3] already blew my mind.

@PeterTaylor Tied. Can we do better?

Mathematica, 67 63
This isn't going to be fast, but I believe it is technically correct.
Round[π,1/Range@1*^6]//.x_:>First/@Split[x,#2≥#&@@Abs[π-{##}]&]

Round[π, x] gives the closest fraction to π in steps of x. This is "listable" so Round[π,1/Range@1*^6] does this for all fractions down to 1/10^6 in order. The resulting list with many "bad" rational approximations is then repeatedly (//.) processed by removing any elements which are farther from π than the preceding one.

Pretty cool, but I can't test it because I don't have Mathematica.

@Keith, here's the logic.  Round[Pi, x] gives the closest fraction to Pi in steps of x.  This is "listable" so Round[Pi,1/Range@1*^6] does this for all fractions down to 1/10^6 in order.  The resulting list with many "bad" rational approximations is then repeatedly (//.) processed by removing any elements which are farther from pi than the preceding one.

Mathematica beating GolfScript. Neat.

In 61: Select[Round[f=Pi,1/Range@1*^6],If[#<f,f=#;True]&@Abs[#-Pi]&] ... but useless given the dominant bias

Yarr, Matie. Thar be magic in this code.

Perl, 77 chars
$e=$p=atan2 0,-1;($f=abs$p-($==$p*$_+.5)/$_)<$e&&($e=$f,say"$=/$_")for 1..1e6

A minor challenge is that Perl doesn't have a built-in π constant available, so I first had to calculate it as atan2(0,-1).  I'm sure this will be beaten by languages more suited for the job, but it's not bad for a language mainly designed for text processing.

You could change 999999 to 1e6 and save 3 chars.

@M42: Thanks!  Down to 82 chars now.

Really nice, $= to get integer. Sorry, I can't upvote twice.

I can't get this to run: String found where operator expected at prog.pl line 1, near "say"$=/$_""

@KeithRandall: You need the -M5.01 switch (and Perl 5.10.0 or later) for the say command.  Sorry for not mentioning that.

JS (95 characters)
for(i=k=1,m=Math;i<1e6;i++)if((j=m.abs((x=m.round(m.PI*i))/i-m.PI))<k)k=j,console.log(x+'/'+i)

It does print 167 lines.

 Python, 96 93 89 characters
a=b=d=1.
while b<=1e6:
 e=3.14159265359-a/b;x=abs(e)
 if x<d:print a,b;d=x
 a+=e>0;b+=e<0

Python, 95 93 characters, different algorithm
p=3.14159265359;d=1
for a in range(3,p*1e6):
 b=round(a/p);e=abs(p-a/b)
 if e<d:print a,b;d=e

note: It was less characters to write p=3.14159265359; than from math import*.  Darn those wordy imports!

Some shortenings: 1.0 -> 1., 10**6 -> 1e6

I have updated with your improvements.  Thanks much.

@KeithRandall, but the second of those makes the output violate the spec.

In second approach there is no need for variable p. That is 4 chars.

@PeterTaylor: I don't understand.  How does it violate the spec?

@Ante: Added your improvement.  Moved it to be my first answer.  Thanks.

You can still save one char by using < instead of <=.

Maybe it's a version-of-Python thing, but for me it's printing the denominator with a trailing .0. Although actually it's separating the numerator and denominator with a newline rather than / anyway, so I don't suppose it makes much difference.

The output format isn't quite right - you need to lose the .0s and put in a /.

Ruby 1.9, 84 characters
m=1;(1..1e6).map{|d|n=(d*q=Math::PI).round;k=(n-q*d).abs/d;k<m&&(m=k;puts [n,d]*?/)}

@Peter Taylor You're right. You have to use Ruby 1.9.

C99, 113 characters
main(d,n){double e=9,p=2*asin(1),c,a=1;for(;n=d*p+.5,c=fabsl(p-a*n/d),d<1e6;++d)c<e&&printf("%d/%d\n",n,d,e=c);}

Need to compile with -lm, and probably full of undefined behaviour, but it works for me.

Scala - 180 chars
import math._
def p(z:Int,n:Int,s:Double):Unit=
if(n==1e6)0 else{val q=1.0*z/n
val x=if(abs(Pi-q)<s){println(z+"/"+n)
abs(Pi-q)}else s
if(Pi-q<0)p(z,n+1,x)else p(z+1,n,x)}
p(3,1,1)

// ungolfed: 457
val pi=math.Pi
@annotation.tailrec
def toPi (zaehler: Int = 3, nenner: Int = 1, sofar: Double=1): Unit = {
  if (nenner == 1000000) ()
  else {
    val quotient = 1.0*zaehler/nenner
    val diff = (pi - quotient)
    val adiff= math.abs (diff)
    val next = if (adiff < sofar) {
      println (zaehler + "/" + nenner)
      adiff
    }
    else sofar
    if (diff < 0) toPi (zaehler, nenner + 1, next)
    else toPi (zaehler + 1, nenner, next)
  }
}

The tailrec annotation is just a check, to verify, that it is tail-recursive, which is often a performance improvement.

I can't get this to work: pi.scala:1 error: not found: value math

Are you using Scala 2.8?

My scala says "unknown version", weird.  On ideone.com, they use 2.8.0 and I still get errors.

Try it at http://www.simplyscala.com/ - works for me. For scala-2.8, replacing math with Math might be sufficient. I mentioned simplyscala on this metathread, if you happen to search for it again: http://meta.codegolf.stackexchange.com/a/401/373

OK, that works.

Mathematica 18 17 chars
I chose to use, as a measure of "best", the number of terms in a continued fraction representation of π.  By this criterion, the best rational approximations of π are its convergents.
There are 10 convergents of  π with a denominator less than one million.  This is fewer than the requested 167 terms, but I am including it here because it may be of interest to others.
Convergents[π, 10]

(* out *)
{3, 22/7, 333/106, 355/113, 103993/33102, 104348/33215, 208341/66317,
312689/99532, 833719/265381, 1146408/364913}

If you really want to see the denominator for the first convergent, it will cost an additional 11 characters:
Convergents[π, 10] /. {3 -> "3/1"}
(* out *)
{"3/1", 22/7, 333/106, 355/113, 103993/33102, 104348/33215,
208341/66317, 312689/99532, 833719/265381, 1146408/364913}

For those who are interested, the following shows the relations among the convergents, partial quotients, and continued fraction expression of convergents of π:
Table[ContinuedFraction[π, k], {k, 10}]
w[frac_] := Row[{Fold[(#1^-1 + #2) &, Last[#], Rest[Reverse[#]]] &[Text@Style[#, Blue, Bold, 14] & /@ ToString /@ ContinuedFraction[frac]]}];
w /@ FromContinuedFraction /@ ContinuedFraction /@ Convergents[π, 10]

Please excuse the inconsistent formatting of the continued fractions.

That's about half-way to a solution, but it's the easiest half. My GolfScript solution hard-codes a suitable representation of the the continued fraction in only 2 characters more.

But you didn't use continued fractions for your solution to this question, did you?

Yes. It was the obvious way to do it.

In addition to being concise, this is much faster than most or all of the other solutions that have been posted.

C# 140 129 chars
double n=3,d=1,e=d;while(n<4e5){double w=n/d-Math.PI,a=Math.Abs(w);if(a<e){e=a;Console.WriteLine(n+"/"+d);}if(w>0)d++;else n++;}

Uncompressed code
var numerator = 3d;
var denominator = 1d;
var delta = 4d;
while (numerator < 4e5)
{
    var newDelta = (numerator / denominator) - Math.PI;
    var absNewDelta = Math.Abs(newDelta);
    if (absNewDelta < delta)
    {
        delta = absNewDelta;
        Console.WriteLine(string.Format("{0}/{1}", numerator, denominator));
    }

    if (newDelta > 0)
    {
        denominator++;
    }
    else
    {
        numerator++;
    }
}

var is not always your friend. By removing it in favour of double you gain the ability to merge declarations, lose the requirement to use double literals, and can save 16 chars. OTOH the question asks for a program, so you'll lose a few to adding a class declaration and a Main method.

J, 69 65
New
]`,@.(<&j{.)/({~(i.<./)@j=.|@-l)@(%~(i:3x)+<.@*l=.1p1&)"0>:_i.1e3

Still a brute force approach but much faster and a tad shorter.
Old
A simple "brute force":
(#~({:<<./@}:)\@j)({~(i.<./)@j=.|@-l)@(%~(i:6x)+<.@*l=.1p1&)"0>:i.1e3

make a list of  a/bs and then discard those that are farther from π for some b'<b.
Note: Change 1e3 to 1e6 for the full list. Go do something else and return later.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Polynomial extrapolation
Task

Given a list of integers a1, a2, …, ak (k ≥ 2) and a positive integer m, write a function or a complete program that calculates the next m numbers of the list. Assume that ai = P(i) where
P(x) = bk-1 xk-1 + bk-2 xk-2 + … + b0
is the unique polynomial of minimum order which fits the points.

Description
Input
If the code is a function, input is given by an integer k, an array a1, a2, …, ak and an integer m.
If the code is a program, input (through stdin) is given by space-separated k a1 a2 … ak m.
You can assume that k ≥ 2 and m > 0.
Calculation
(Of course, the code can calculate the result in different way, but the result should be same.)
Find the polynomial P(x) which satisfies ai = P(i) for all 1 ≤ i ≤ k and has a degree of (no more than) k - 1. For example, if a list is 1,2,3,4,5, then P(x) = x. If a list is 1,4,9,16,25, then P(x) = x2.
Then, calculate ak+1 = P(k+1), ak+2 = P(k+2), …, ak+m = P(k+m). These are the results.
Output
If the code is a function, return an array [ak+1, ak+2, …, ak+m].
If the code is a full program, print those numbers to stdout, separated by an any character you want.

I think you should require some separator for the output: 1 4 9 16 25 is much less ambiguous than 1491625.

@IlmariKaronen OK then.

NB This is almost a duplicate of http://codegolf.stackexchange.com/questions/1230/implement-shamirs-secret-sharing-reconstruction . The differences are that it's over a field of characteristic 0; that the x-coords are implicit; and that it asks for extrapolation to k+1, ... k+m rather than to 0.

Golfscript, 46 42 40 38 chars
~])\({[{.@-\}*])\}*;]-1%){0\{+.}/p]}*;

This uses a simple difference table approach, which is described in more detail on my GolfScript blog.

+100: You beat Ilmari's 40 char-or-less challenge :)

Bounty awarded. Congratulations! Now I just need to learn enough GolfScript to be able to understand your code. :)

@IlmariKaronen, I might write it up for my GolfScript blog in a few days. The -2% is quite interesting in that it's something I didn't really see much point to before.

@IlmariKaronen, code dissection posted to my blog.

Maple, 41 chars
c:=(k,a,m)->interp([$1-k..0],a,x)$x=1..m;

For example, c(3, [1, 2, 4], 4) returns 7, 11, 16, 22.
This function interprets the spec literally, taking both k and a as separate arguments.  If the list a does not have exactly k elements, an error occurs.  For convenience, here's a 45-char version that omits k from the argument list:
c:=(a,m)->interp([$1-nops(a)..0],a,x)$x=1..m;

I was first thinking of trying this in Perl, but hell, let's use the right tool for the job.

BTW, since this is code golf, 'the right tool' is golfscript. :P

@JiminP: OK, challenge accepted. The first person to solve this task in 40 or fewer chars in GolfScript gets a 100 rep bounty from me.

@PeterTaylor When inputs are integers, outputs might always be integers (there's a way to calculate outputs by using only integers), even though I don't have any proofs.

Challenge met. Don't feel obliged to give me the bounty, though; I'm doing ok for rep already.

@PeterTaylor: I'll give it to you anyway, it's not like I'm starved for rep either.  And I did promise.  (I assume I have to wait until the question is old enough, though, since I don't see any "start a bounty" link yet.)

Jelly, 18 bytes, language postdates challenge
Iß;@Ḣ+\øṁ⁹µL?
çUḣU

Try it online!
Jelly's functions only support up to two arguments, so I don't take in k (which is redundant) as an argument. I hope that's acceptable. The program defines a function 2ŀ that obeys the specification in the question.
Explanation
Helper function 1ŀ (takes input λ, ρ, and expands λ by ρ elements):
Iß;@Ḣ+\øṁ⁹µL?
       ø  µ ? If
           L    {λ} is nonempty,
              then:
I               take differences of consecutive elements of {λ};
 ß              call 1ŀ recursively on this value and {ρ};
  ;@            prepend
    Ḣ           the first element of {λ};
     +\         and take the cumulative sum {and return it}.
              Otherwise:
        ṁ⁹      {return} {0} repeated ρ times.

This is fairly magical in the way in which Jelly happens to pick out the exactly values I need it to operate on at every stage. Some of it is the result of me manipulating things; in particular, the unusual choice ø for the separator (rather than the more usual µ) means that all implicit arguments are set to 0, which is fairly handy in this case. However, I have no idea why ;@Ḣ parses the way it does, but it seems to work…
Main function 2ŀ (takes input λ, ρ, and returns the next ρ elements of λ):
çUḣU
ç             Call 1ŀ on {λ} and {ρ};
 U            reverse it;
  ḣ           take the first {ρ} elements;
   U          and reverse it {and return that value}.

This is just massaging the output into the form requested (if we were allowed to return the terms we were already given, that would remove a whole 5 bytes). Jelly doesn't have a "last n elements" function; of the various ways to synthesize it out of other functions, UḣU is convenient here because it happens to pick up ρ as a default argument.

Golfscript, 51 characters
Similar approach to Peter's one.
~])\-1%[{(.@{.@\-}%\;.,}do;]-1%\[0]\*\{\{+.}%\;}%;p

When run on input
2 3 12 35 78
4

it yields the result
[147 248 387 570]

There are still possible places where the solution might be golfable further.

Scala, 128 bytes
m=>Stream.iterate(_)(a=>a.tail.lazyZip(a)map(_-_)).takeWhile(Nil!=).:\(Seq.fill(m)(0))((a,b)=>b.scanLeft(a(0))(_+_))takeRight(m)

Try it online!

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Justify a text by adding spaces
Given this text

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

write the shortest program that produces the same text justified at 80 character. The above text must look exactly as:
Lorem ipsum dolor sit amet,  consectetur adipisicing elit, sed do eiusmod tempor
incididunt ut  labore et  dolore magna aliqua.  Ut  enim ad  minim veniam,  quis
nostrud exercitation ullamco laboris nisi ut  aliquip ex  ea  commodo consequat.
Duis aute irure dolor in  reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur.  Excepteur sint occaecat cupidatat non proident,  sunt in
culpa qui officia deserunt mollit anim id est laborum.

Rules:

words must not be cut
extra spaces must be added

after a dot.
after a comma
after the shortest word (from left to right)
the result must not have more than 2 consecutive spaces

last line is not justified.
lines must not begin with comma or dot.
provide the output of your program

winner: The shortest program.
note: The input string is provided on STDIN as one line (no line feed or carriage return)
update:
The input string can be any text with word length reasonnable (ie. not more than 20~25 char) such as:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed non risus. Suspendisse lectus tortor, dignissim sit amet, adipiscing nec, ultricies sed, dolor. Cras elementum ultrices diam. Maecenas ligula massa, varius a, semper congue, euismod non, mi. Proin porttitor, orci nec nonummy molestie, enim est eleifend mi, non fermentum diam nisl sit amet erat. Duis semper. Duis arcu massa, scelerisque vitae, consequat in, pretium a, enim. Pellentesque congue. Ut in risus volutpat libero pharetra tempor. Cras vestibulum bibendum augue. Praesent egestas leo in pede. Praesent blandit odio eu enim. Pellentesque sed dui ut augue blandit sodales. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Aliquam nibh. Mauris ac mauris sed pede pellentesque fermentum. Maecenas adipiscing ante non diam sodales hendrerit. Ut velit mauris, egestas sed, gravida nec, ornare ut, mi. Aenean ut orci vel massa suscipit pulvinar. Nulla sollicitudin. Fusce varius, ligula non tempus aliquam, nunc turpis ullamcorper nibh, in tempus sapien eros vitae ligula. Pellentesque rhoncus nunc et augue. Integer id felis. Curabitur aliquet pellentesque diam. Integer quis metus vitae elit lobortis egestas. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Morbi vel erat non mauris convallis vehicula. Nulla et sapien. Integer tortor tellus, aliquam faucibus, convallis id, congue eu, quam. Mauris ullamcorper felis vitae erat. Proin feugiat, augue non elementum posuere, metus purus iaculis lectus, et tristique ligula justo vitae magna. Aliquam convallis sollicitudin purus. Praesent aliquam, enim at fermentum mollis, ligula massa adipiscing nisl, ac euismod nibh nisl eu lectus. Fusce vulputate sem at sapien. Vivamus leo. Aliquam euismod libero eu enim. Nulla nec felis sed leo placerat imperdiet. Aenean suscipit nulla in justo. Suspendisse cursus rutrum augue. Nulla tincidunt tincidunt mi. Curabitur iaculis, lorem vel rhoncus faucibus, felis magna fermentum augue, et ultricies lacus lorem varius purus. Curabitur eu amet.

Why ask people to provide the output of their program? Are you that worried about people failing to check their results before posting?

I'm tempted to provide a php program which consists of the output text. ;-)
Seriously though, the spaces on the second line of the output text seem to have been added to the spaces at random? Is there some pattern to it that I'm not seeing, and if not, how can we be expected to produce exactly that output for the given input?

@Gareth: Sorry, my bad. I made a mistake, is after the comma, not after incididunt. Question edited.

@Peter Taylor: Just because I'm not able to test all languages.

Does the program have to work also for inputs other than that one paragraph of Lipsum?

@Ilmari Karonen: Yes, the input string can be anything.

Just after submitting my answer I saw that you changed the task by removing the restriction to the input string. Can you please adjust the question itself. I'll then try to rewrite my answer to work for any input.

What should the program do if the text cannot be justified within the rules given above (e.g. one word with more than 80 charcters or two words with 50 each, ...)?

@Howard: see my update

Thank you for clarifying. But consider also a text with e.g. 4 words with 20 caracters each. You cannot justify it according to your rules.

Perl, 94 chars
for(/(.{0,80}\s)/g){$i=1;$i+=!s/^(.*?\.|.*?,|(.*? )??\S{$i}) \b/$1  /until/
|.{81}/;chop;say}

Run with perl -nM5.01.  (The n is included in the character count.)
The code above is the shortest I could make that could handle any curveballs I threw at it (such as one-letter words at the beginning of a line, input lines exactly 80 chars long, etc.) exactly according to spec:
Lorem ipsum dolor sit amet,  consectetur adipisicing elit, sed do eiusmod tempor
incididunt ut  labore et  dolore magna aliqua.  Ut  enim ad  minim veniam,  quis
nostrud exercitation ullamco laboris nisi ut  aliquip ex  ea  commodo consequat.
Duis aute irure dolor in  reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur.  Excepteur sint occaecat cupidatat non proident,  sunt in
culpa qui officia deserunt mollit anim id est laborum.

I'm  tempted to  provide a  php  program which consists of  the output text. ;-)
Seriously though,  the spaces on the second line of the output text seem to have
been added to  the spaces at  random? Is  there some pattern to  it that I'm not
seeing,  and if  not,  how can we be expected to produce exactly that output for
the given input?

(With apologies to Gareth for using his comment as additional test input.)
The following 75-char version works well enough to produce the sample output from the sample input, but can fail for other inputs.  Also, it leaves an extra space character at the end of each the output line.
for(/(.{0,80}\s)/g){s/(.*?\.|.*?,|.*? ..) \b/$1  /until/.{81}/||s/
//;say}

Both versions will loop forever if they encounter input that they can't justify correctly.  (In the longer version, replacing until with until$i>80|| would fix that at the cost of seven extra chars.)

Ah, I should have started with a perl solution ;-) This language is of course really good for such a task.

I got Quantifier in {,} bigger than 32766 in regex; marked by <-- HERE in m/^(.*?\.|.*?,|(.*? )??\S{ <-- HERE 32767}) \b/ for the second text.

@M42: That's because the second example text cannot be justified according to the rules.  If I add in the $i>80 check, it expands the 11th line to pede  pellentesque  fermentum.  Maecenas  adipiscing  ante  non  diam  sodales, which is only 78 chars long, and then gives up since each word (except the last) is followed by two spaces.

Ruby, 146 characters
$><<gets.gsub(/(.{,80})( |$)/){$2>""?(s=$1+$/;(['\.',?,]+(1..80).map{|l|"\\b\\w{#{l}}"}).any?{|x|s.sub! /#{x} (?=\w)/,'\& '}while s.size<81;s):$1}

It prints exactly the desired output (see below) if the given text is fed into STDIN.
Lorem ipsum dolor sit amet,  consectetur adipisicing elit, sed do eiusmod tempor
incididunt ut  labore et  dolore magna aliqua.  Ut  enim ad  minim veniam,  quis
nostrud exercitation ullamco laboris nisi ut  aliquip ex  ea  commodo consequat.
Duis aute irure dolor in  reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur.  Excepteur sint occaecat cupidatat non proident,  sunt in
culpa qui officia deserunt mollit anim id est laborum.

Edit: Just after submitting my first solution I saw in the comments that it is required that any input string can be processed. The previous answer was only 95 characters but did not fulfill this requirement:
r=gets.split;l=0;'49231227217b6'.chars{|s|r[l+=s.hex]+=' '};(r*' ').gsub(/(.{,80}) ?/){puts $1}

If I'm not mistaken, you're using the same cheat as I thought of (encoding the locations of the double-spaced words in the example output).  Note that M42 has clarified that the programs should cope with other inputs too.

@Ilmari Karonen Yes, I saw that after submitting. See my edit and comments above. Going back to the golf course...