title: 12 Days of Christmas Lyrics

text:
# Question
Title: 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

# Answer
> 28 votes
## 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..>>>>>.<<<<<-->->--->>>>>>>>>>>>>>>>>>>-]
   <<<<<<<<<<<<<<<<<<<<<<..>>>>>>>->+
   [>+>>>>>>>>>>>>>[>]+[<]<<<<<<<<<<<<<-]>[<+>-]<<
]

```

# Answer
> 12 votes
# 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.

# Answer
> 10 votes
## 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". :)

# Answer
> 7 votes
## 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.

# Answer
> 7 votes
# 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);}

```

# Answer
> 6 votes
# 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.

# Answer
> 5 votes
## 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

# Answer
> 5 votes
## 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

# Answer
> 5 votes
## 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.

# Answer
> 4 votes
## 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

```

# Answer
> 4 votes
# 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

```

# Answer
> 4 votes
# 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.

# Answer
> 3 votes
## 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));}}}

```

# Answer
> 2 votes
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/')));

```

# Answer
> 2 votes
# 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;
    }

}

```

# Answer
> 2 votes
## 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

```

# Answer
> 2 votes
# ///, 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.

# Answer
> 1 votes
# 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.

# Answer
> 1 votes
## 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}

```

# Answer
> 1 votes
# 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.

# Answer
> 1 votes
# 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.

# Answer
> 1 votes
## 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!

# Answer
> 1 votes
# 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`
* fi**ve** -\> fi**f**th; twel**ve** -\> twel**f**th (that's a mini-etymology lesson for you)
* nin**e** -\> ninth; eigh**t** -\> eighth

# Answer
> 1 votes
# 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!

# Answer
> 0 votes
# 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.

# Answer
> 0 votes
# 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.)

---
Tags: code-golf, kolmogorov-complexity
---


title: Rounding a range

text:
# Question
Title: Rounding a range
You have a line with two endpoints `a` and `b` (`0 ≤ a < b`) on a 1D space. When `a` or `b` has a fractional value, you want to round it to an integer.

One way to do this is to round `a` and `b` each to its nearest integer, but this has a problem that the length of the rounded range (`L`) can vary while `b - a` stays the same. For example,

```
b - a = 1.4
(a, b) = (1, 2.4) -> (1, 2), L = 1
         (1.2, 2.6) -> (1, 3), L = 2

```

We want to find a way to round `(a, b)` so that `L` always has the same value `⌊b - a⌋` while the rounded pair `(ra, rb)` is closest to `(a, b)`.

With `(a, b) = (1.2, 2.6)`, we can consider two candidates of `(ra, rb)` with `L = ⌊2.6 - 1.2⌋ = 1`. One is `(1, 2)` and the other is `(2, 3)`. `(1, 2)`'s overlapping range with `(a, b) = (1.2, 2.6)` is `(1.2, 2)`, while `(2, 3)` overlaps at `(2, 2.6)`. `(1, 2)` has a larger overlapping range (`(1.2, 2)` vs `(2, 2.6)`), so in this case we choose `(1, 2)`.

Sometimes there are two options with the same overlapping length. For example, `(0.5, 1.5) -> (0, 1), (1, 2)`. In such cases, either could be, but one should be, chosen.

### Examples

```
0 ≤ a < b
b - a ≥ 1
(a, b) -> (ra, rb)

(1, 2) -> (1, 2)
(1, 3.9) -> (1, 3)
(1.1, 4) -> (2, 4)
(1.2, 4.6) -> (1, 4)
(1.3, 4.7) -> (1, 4) or (2, 5)
(1.4, 4.8) -> (2, 5)
(0.5, 10.5) -> (0, 10) or (1, 11)

```

# Answer
# Python, 44 bytes

```
lambda a,b:(m:=(a+b+1-(l:=int(b-a)))//2,m+l)
```

Attempt This Online!

## Old Python, 50 bytes

```
lambda a,b:(m:=(a+b+~(l:=int(b-a))%2)//2-l//2,m+l)
```

Attempt This Online!

## Old Python, 56 bytes

```
lambda a,b:((m:=(a+b+~(l:=int(b-a))%2)//2)-l//2,m--l//2)
```

Attempt This Online!

## How?

The basic idea is: If the required length `l` is even round the midpoint and move `l/2` in both directions. If `l` is odd round the midpoint to the nearest half integer instead.
> 7 votes

# Answer
# Factor \+ `math.unicode`, 44 bytes

```
[ 2dup - ⌊ -rot 1 + + over - 2 /i tuck + ]

```

Try it online!

Takes input as `b a`. Port of loopy walt's Python answer.
> 3 votes

# Answer
# 05AB1E, ~~16~~ 14 bytes

```
O>I`αï©-2÷D®+‚

```

-2 bytes porting *@loopyWalt*'s Python answer; make sure to upvote him as well!

Try it online or verify all test cases.

**Explanation:**

```
O              # Sum the (implicit) input-pair
 >             # Increase it by 1
  I            # Push the input-pair again
   `           # Pop and push both values separated to the stack
    α          # Take the absolute difference between both
     ï         # Cast it to an integer to floor it
      ©        # Sort this value in variable `®` (without popping)
       -       # Subtract it from the earlier sum+1
        2÷     # Integer-divide it by 2
          D    # Duplicate this
           ®+  # Add `®` to the copy
             ‚ # Pair the two values together
               # (after which it is output implicitly as result)

```
> 3 votes

# Answer
# PARI/GP, 34 bytes

```
f(a,b)=[m=(a+b+1-l=(b-a)\1)\2,m+l]
```

Attempt This Online!

A port of loopy walt's Python answer.

---

# PARI/GP, 48 bytes

```
f(a,b)=[a,b]\1+if(a%1>b%1,[1,0],[t=a%1+b%1>1,t])
```

Attempt This Online!
> 2 votes

# Answer
# Desmos, 62 bytes

```

f(a,b)=(A,\floor(b-a)+A)+\{\ceil(b)-b<a-A,0\}(1,1)
A=floor(a)

```

Takes input as function parameters and returns a point `(ra,rb)`

Try it on Desmos!
> 2 votes

# Answer
# Charcoal, 26 bytes

After messing around trying to find an arithmetic solution I came up with the following:

```
Ｎθ≔Ｅ⁺Ｎ⟦±θ⊕θ⟧⌊ιηＩ÷⟦↨η±¹Ση⟧²

```

Try it online! Link is to verbose version of code.

Rather than trying to be clever with vectorised arithmetic, I rewrote it to use variables instead. It still came out at 26 bytes:

```
ＮθＮη≔⌊⁻ηθζ≧⁺⊕θηＩ÷⟦⁻ηθ⁺ηζ⟧²

```

Try it online! Link is to verbose version of code.

A direct port of @loopywalt's Python answer turns out to also be 26 bytes:

```
ＮθＮη≔⌊⁻ηθζ≔÷⁻⊕⁺ηθζ²εＩ⟦ε⁺εζ

```

Try it online! Link is to verbose version of code. Note that because it does the integer division by 2 earlier it doesn't need to explicitly close the output list, saving a byte.
> 2 votes

---
Tags: code-golf, math, number
---


title: Shortest restricted superstring

text:
# Question
Title: Shortest restricted superstring
Given two sets of strings, \\$ D \\$ and \\$ R \\$, find the shortest string which contains every string in \\$ D \\$, but contains none of the strings in \\$ R \\$.

There are almost always multiple possible outputs; you should output at least one of them, but you can output more.

You can assume this is possible with the inputs you are given; i.e., none of the strings in \\$ R \\$ are substrings of those in \\$ D \\$.

Note that the result \\$ s \\$ may have to include characters which are not present in any of the strings in \\$ D \\$. For example, when \\$ D = \\{\text a, \text b\\} \\$ and \\$ R = \\{\text {ab}, \text {ba}\\} \\$, there must be at least one other character in the output - it would have to be something like \\$ \text {axb} \\$ or \\$ \text {bxa} \\$.

Furthermore, in order to simplify dealing with the case above, you may choose a character that you can assume to never be present in the input, but is allowed in the output. For example, you may restrict your input to always use letters, but sometimes give outputs containing underscores as well as letters.

"String" here is used in an abstract sense: you may operate on actual strings of characters, but also on lists of positive integers, or any other reasonable domain.

This is , so the shortest code in bytes wins.

## Test cases

| \\$ D \\$ | \\$ R \\$ | output |
| --- | --- | --- |
| (empty set) | (empty set) | (empty string) |
| (empty set) | `a` | (empty string) |
| `a` | (empty set) | `a` |
| `ab`, `bc` | (empty set) | `abc` |
| `a`, `b` | `ab`, `ba` | `axb` or `a$b` or etc. |
| `ab`, `bc` | `abc` | `bcab` or `abbc` |
| `ab`, `cd` | `bc` | `cdab` |
| `ab`, `a` | `c` | `ab` |
| `code`, `golf`, `fig`, `egg` | `igo` | `codeggolfig` |
| `a`, `b`, `c` | `abc`, `bac`, `ca` | `cba` or `acb` |
| `a`, `b`, `c` | `ab`, `bc`, `ac`, `ba`, `cb`, `ca` | `a$b$c` etc. |

*This question came to me while attempting to optimise the substring check in this answer.*

# Answer
# Python, 150 bytes

```
f=lambda D,R,m=min:m([h for d in D for e in f(D-{d},R,sorted)for x in range(len(d)+2)if(d in(h:=(d+"_")[:x]+e))>any(r in h for r in R)]or[""],key=len)
```

Attempt This Online!

## Old Python, 152 bytes

```
lambda D,R:min((g:=lambda D:[h for d in D for e in g(D-{d})for x in range(len(d)+2)if(d in(h:=(d+"_")[:x]+e))>any(r in h for r in R)]or[""])(D),key=len)
```

Attempt This Online!

## Old Python, 158 bytes

```
lambda D,R:min((g:=lambda D:[h for d in D for e in g(D-{d})for x in range(len(d)+2)if d in(h:=(d+"_")[:x]+e)and not any(r in h for r in R)]or[""])(D),key=len)
```

Attempt This Online!
> 5 votes

# Answer
# JavaScript (ES6),  ~~159~~  157 bytes

Expects `[D,R]`. Assumes that the input words are made of letters and uses `0` as the separator.

```
f=(b,a=b[q=0],p='')=>a.map((v,i,g)=>(g=v=>f(b,a.filter((_,k)=>k-i),p+v)&&v&&g(v.slice(1)))(0+v))+[p[q.length]]||b.some((a,i)=>a.some(w=>!p.match(w)^i))?q:q=p

```

Try it online!

### Commented

```
f = (                    // f is a recursive function using:
  b,                     //   b[] = [D[], R[]]
  a = b[q = 0],          //   a[] = D[],
                         //   q = final output (initially not a string)
  p = ''                 //   p = current output
) =>                     //
a.map((v, i, g) =>       // for each string v at position i in a[]:
  ( g = v =>             //   g is a recursive function taking a string v
    f(                   //     do a recursive call to f:
      b,                 //       pass b[] unchanged
      a.filter((_, k) => //       pass a copy of a[] ...
        k - i            //       ... with the i-th entry removed
      ),                 //
      p + v              //       append v to p
    )                    //     end of recursive call
    && v                 //     unless v is an empty string:
    && g(v.slice(1))     //       do a recursive call to g with v.slice(1)
  )(0 + v)               //   initial call to g with a leading "0" added to v
)                        // end of map(), whose result is coerced to a string
+ [p[q.length]] ||       // if a[] was empty and p[q.length] is undefined:
  b.some((a, i) =>       //   for each entry a[] at position i in b[]:
    a.some(w =>          //     for each string w in a[]:
      !p.match(w)        //       1 if w is not found in p / 0 otherwise
      ^ i                //       XOR'ed with the expected result
                         //       (0 for D[], 1 for R[])
    )                    //     end of inner some()
  )                      //   end of outer some()
  ? q : q = p            //   update q to p if the above test didn't fail

```
> 4 votes

# Answer
# Python, ~~172~~ ~~168~~ 164 bytes

```
from itertools import*
f=lambda D,R:next(x for i in count()for x in map("".join,product(*[{"$"}.union(*D|R)]*i))if all(j-(y in x)for j,X in[(0,D),(1,R)]for y in X))
```

Attempt This Online!
> 3 votes

# Answer
# 05AB1E, ~~18~~ 19 bytes

```
JDu«æ€œ˜é.Δ¹åy²å_«P

```

+1 byte as bug-fix for test cases that require more than 1 random filler-character (e.g. `[["a","b","c"],["ab","ba","ac","ca","bc","cb"]]`).

Assumes the input are lowercase letters, and uses uppercase letters as potential filler-characters if necessary (e.g. for the fifth test case).

Try it online or verify (almost) all test cases.

**Explanation:**

```
J                 # Join the (implicit) first input-list together to a string
 Du«              # Append an uppercase copy of this string
    æ             # Get the powerset of this string
     €œ           # Get the permutations of each inner string
       ˜          # Flatten this list of list of strings
        é         # Sort it by length
         .Δ       # Find the first which is truthy for:
           ¹      #  Push the first input-list
            å     #  Check for each inner string if it's a substring
           y      #  Push the string we're filtering over again
            ²     #  Push the second input-list
             å    #  Check for each inner string again if it's a substring
              _   #  Invert the booleans to check all of them were falsey
               «  #  Merge the two lists together
                P #  Check that all are truthy by taking the product
                  # (after which the found result is output implicitly)

```
> 3 votes

# Answer
# Python3, 261 bytes:

```
E=enumerate
def f(d,c=''):
 if not d:yield c;return
 for i,a in E(d):
  j=d[:i]+d[i+1:]
  yield from[*f(j,c+a),*f(j,c+'$'+a)]
  for x,y in E(a):
   if c[-1*x:]==a[:x]:yield from f(j,c+a[x:])
lambda d,r:min([i for i in f(d)if all(m not in i for m in r)],key=len)

```

Try it online!
> 2 votes

# Answer
# Python 3, 141 bytes

```
f=lambda d,r,s='':d[len(s):]and min([s*(all(w in s for w in d.split())-any(w in s for w in r.split()))or f(d,r,s+c)for c in{*d}],key=len)or d

```

Try it online!

Recursive solution trying all possible permutations and returning the shortest one. Takes each input as a single space-separated string. Also uses \[space\] as the special character in the output. The longest test-case times out, but should work in principle.
> 2 votes

# Answer
# Charcoal, 32 bytes

```
⊞υωＦυ¿¬ⅉ¿›⬤θ№ικ⊙η№ικ⟦ι⟧Ｆ⪫θ_⊞υ⁺ικ

```

Try it online! Link is to verbose version of code. Brute-force, so exponentially slow in the length of the output. Uses `_` as the filler character. Explanation:

```
⊞υωＦυ

```

Start a breadth-first search of all strings containing the input characters or `_`.

```
¿¬ⅉ

```

Stop when a string has been output.

```
¿›⬤θ№ικ⊙η№ικ⟦ι⟧

```

If the current string satisfies the inputs then print it now.

```
Ｆ⪫θ_⊞υ⁺ικ

```

Otherwise, for each character in the inputs or `_`, append that character to the current string and push the result to the search list.
> 2 votes

---
Tags: code-golf, string, optimization, subsequence
---


title: Infinite Candle Sequence

text:
# Question
Title: Infinite Candle Sequence
I have a cake shop that specialises in birthday cakes. The cakes that I sell must have candles placed in a circle. You would probably think I can just divide 360° by the number of candles, but the machine for placing candles is quite unique; it uses a list of numbers representing positions of candles, placing them one-by-one until it reaches the desired amount. Furthermore, it can only store numbers as a binary fraction of turns, ie. \\$n/2^m\\$ where \\$\\{n,m \in \Bbb Z^{0+} | n \< m \\}\\$.

Since I want the candles placed as evenly as possible, I've devised a method for working out where to place each candle.

The first candle goes at position 0.
In order to balance the cake, the next goes at 1/2.
The next two candles go in the remaining gaps, so 1/4, 3/4.
The next four use the sequence so far to define the order. So 1/8, 5/8, 3/8, 7/8.
Ad infinitum.

To put it more generally:

$$ \begin{aligned} f(0) &= 0 \\ f(n) &= f(n - 2 ^{\lfloor \log\_2{n} \rfloor}) + 2 ^ {-\lfloor \log\_2{n} \rfloor - 1} \end{aligned} $$

Create for me a program or function to create this sequence.

My machine has a small hard drive (I mean *really* small), so the code should be as short as possible.

## Output

The output should follow standard sequence output. That is, either output the entire sequence (print them one by one or return a list or generator representing the sequence), or given an index \\$n\\$ (0 or 1 indexed) return the \\$n\\$th entry or every entry up to the \\$n\\$th.

The entries can be either represented as a simplified fraction (numerator and denominator separated by `/`) or decimal (rounding errors are acceptable).

The first 64 terms as fractions are

```
0
1/2
1/4
3/4
1/8
5/8
3/8
7/8
1/16
9/16
5/16
13/16
3/16
11/16
7/16
15/16
1/32
17/32
9/32
25/32
5/32
21/32
13/32
29/32
3/32
19/32
11/32
27/32
7/32
23/32
15/32
31/32
1/64
33/64
17/64
49/64
9/64
41/64
25/64
57/64
5/64
37/64
21/64
53/64
13/64
45/64
29/64
61/64
3/64
35/64
19/64
51/64
11/64
43/64
27/64
59/64
7/64
39/64
23/64
55/64
15/64
47/64
31/64
63/64

```

and as decimal

```
0
0.5
0.25
0.75
0.125
0.625
0.375
0.875
0.0625
0.5625
0.3125
0.8125
0.1875
0.6875
0.4375
0.9375
0.03125
0.53125
0.28125
0.78125
0.15625
0.65625
0.40625
0.90625
0.09375
0.59375
0.34375
0.84375
0.21875
0.71875
0.46875
0.96875
0.015625
0.515625
0.265625
0.765625
0.140625
0.640625
0.390625
0.890625
0.078125
0.578125
0.328125
0.828125
0.203125
0.703125
0.453125
0.953125
0.046875
0.546875
0.296875
0.796875
0.171875
0.671875
0.421875
0.921875
0.109375
0.609375
0.359375
0.859375
0.234375
0.734375
0.484375
0.984375

```

# Answer
# Python, 31 bytes

```
f=lambda a:a and(f(a//2)+a%2)/2
```

Attempt This Online!

Returns the nth term (0-based) as a float.

# Python, 54 bytes

```
a=b=0
while[print(int(bin(a)[:1:-1],2)/-~b)]:a+=1;b|=a
```

Attempt This Online!

Prints decimal fractions indefinitely.

How?

One can check that if we simply count 0,1,2,3,4 ... and mirror the binary representation at the dot we get 0.0 -\> 0.0, 1.0 -\> 0.1, 10.0 -\> 0.01, 11.0 -\> 0.11, 100.0 -\> 0.001 ... which happens to be precisely what is needed.
> 13 votes

# Answer
# JavaScript (ES6), 32 bytes

Returns the \\$n\\$-th term, 0-indexed.

```
f=(n,p=0)=>n?f(n>>1,2*p|n&1)/2:p

```

Try it online!

### 23 bytes

Using loopy walt's approach, this can be further optimized to:

```
f=n=>n&&(f(n>>1)+n%2)/2

```

Try it online!
> 6 votes

# Answer
# Charcoal, 8 bytes

```
Ｉ↨·⁵↨⊗Ｎ²

```

Try it online! Link is to verbose version of code. Outputs the 0-indexed `n`th term. Explanation: Another port of @loopywalt's Python answer.

```
      Ｎ     Input `n`
     ⊗      Doubled
    ↨  ²    Convert to base 2
 ↨·⁵        Interpret as base 0.5
Ｉ           Cast to string
            Implicitly print

```
> 5 votes

# Answer
# C (gcc), <sup>~~63~~</sup> 60 bytes

```
float d,v;float f(n){for(d=1,v=0;n;n/=2,d*=2)v+=v+n%2;v/=d;}

```

Try it online!

*Saved 3 bytes thanks to Dominic van Essen!!!*

Inputs integer \\$n\\$.
Returns the \\$n^\text{th}\\$ element in the sequence as a floating point number.
> 5 votes

# Answer
# Husk, 4 bytes

```
½B.ḋ

```

(or, equivalently, `B.ḋD`) Try it online!

Outputs n-th term of sequence.

Same approach as Neil's variant of loopy walt's answer.

```
   ḋ    # convert to binary digits
 B.     # convert from base-0.5
½       # halve

```

This is *much* shorter than calculating the numerator (OEIS A030101: `mȯḋ↔ḋN`) and denominator (OEIS A062383: `mö`^2←LḋN`) separately & combining (`mȯ§/o`^2Lḋ↔ḋN`).
> 5 votes

# Answer
# Jelly, 4 bytes

```
BHḅ.

```

A monadic Link that accepts a non-negative integer and yields the element of the binary Van der Corput sequence at that 0-indexed index.

**Try it online!**

### How?

Uses the definition given at Wikipedia's entry for a Van der Corput sequence using base two:

$$\text{Corput}\_2(n) = \sum\_{k=0}^{\text{bitLength}(n)-1}{\text{bit}(n, k)\cdot 2^{-k-1}}$$ $$\text{Corput}\_2(n) = \sum\_{k=0}^{\text{bitLength}(n)-1}{\frac{1}{2}\text{bit}(n, k)\cdot \frac{1}{2^k}}$$

```
BHḅ. - Link: non-negative integer, I
B    - binary digits of I
 H   - halve them all
   . - a half
  ḅ  - convert (the list of zeros and halves) from base (one half)

```
> 5 votes

# Answer
# Factor, ~~54~~ 42 bytes

```
[ >bin 48 v-n 0 [ [ 2 / ] bi@ + ] reduce ]

```

Try it online!

```
                   ! 9
>bin               ! "1001"
48                 ! "1001" 48
v-n                ! { 1 0 0 1 }                      (convert from binary string to array)
0                  ! { 1 0 0 1 } 0                    (push seed value for reduce)
[ [ 2 / ] bi@ + ]  ! { 1 0 0 1 } 0 [ [ 2 / ] bi@ + ]  (push base 1/2 convert quotation)
reduce             ! 9/16
! =========================================================================================
                   !          (now let's look at each iteration of reduce)
                   ! 0 1      (iteration 1)
[ 2 / ] bi@        ! 0 1/2    (divide both by 2)
+                  ! 1/2
                   ! 1/2 0    (iteration 2)
[ 2 / ] bi@        ! 1/4 0
+                  ! 1/4
                   ! 1/4 0    (iteration 3)
[ 2 / ] bi@        ! 1/8 0
+                  ! 1/8
                   ! 1/8 1    (iteration 4 [final])
[ 2 / ] bi@        ! 1/16 1/2
+                  ! 9/16

```
> 4 votes

# Answer
# Retina 0.8.2, 64 bytes

```
\d+
$*
+`(1+)\1
$+0
01
1
.+
$&/$.&$*01
1
10
+`01
110
0

1+|^
$.&

```

Try it online! Link is to test suite that generates the results for `0`..`n` (inclusive, 0-indexed). Explanation: Port of @loopywalt's Python answer.

```
\d+
$*

```

Convert to unary.

```
+`(1+)\1
$+0
01
1

```

Convert to binary.

```
.+
$&/$.&$*01

```

Divide by the next power of `2`.

```
1
10
+`01
110
0

```

Convert to unary, but reading backwards (which is why the power of `2` "ended" in `1`).

```
1+|^
$.&

```

Convert to decimal, but fix up an input of `0` to output `0`.
> 3 votes

# Answer
# PARI/GP, 23 bytes

```
f(a)=if(a,f(a\2)+a%2)/2
```

Attempt This Online!

A port of loopy walt's Python answer.
> 3 votes

# Answer
# Wolfram Language (Mathematica), ~~38~~ 33 bytes

```
If[#<1,0,#0@⌊#/2⌋+#~Mod~2]/2&

```

Try it online!

*-5 bytes thanks to att*
> 3 votes

# Answer
# K (ngn/k), 8 bytes

Double n, get base 2 representation and interpret as base 0.5

```
0.5/2\2*

```

Try it online!
> 3 votes

# Answer
# Wolfram Language (Mathematica), 33 bytes (-11 from Steffan, -13 from ATT)

```
#~IntegerReverse~2/2^BitLength@#&

```

Try it online!

## Explanation

`#~IntegerReverse~` Take the number reversed

`2` in base 2,

`/` divided by

`2^BitLength@#` the nearest greater power of 2 to the input.

If you want to output a list:

# Wolfram Language (Mathematica), 48 bytes

```
Table[i~IntegerReverse~2/2^BitLength@i,{i,0,#}]&

```

Try it online!
> 2 votes

# Answer
# Raku, 24 bytes

```
{:2("0."~.base(2).flip)}

```

Try it online!

Pity the radix syntax doesn't support non-integer bases.

### Explanation

```
{                      }  # Anonymous code block
         .base(2)          # Convert to base 2
                 .flip     # Reverse
    "0."~                  # Prepend with 0.
 :2(                  )    # Convert back to base 2

```
> 2 votes

# Answer
# Vyxal, ~~5~~ 4 bytes

```
b½.β

```

Try it Online!

## How?

```
b    # Get the binary digits of the (implicit) input
 ½   # halve them all
   β # Convert from base
  .  # 1/2

```

*-1 byte thanks to emanresu A*
> 1 votes

# Answer
# Desmos, ~~65~~ 64 bytes

```
f(n)=total(.5mod(floor(nl),2)l)
l=.5^{[floor(log_2(n+0^n))...0]}

```

Try it on Desmos!

*-1 byte thanks to Aiden Chow*
> 1 votes

# Answer
# ayr, 9 bytes

Pretty boring solution, but it works

```
.5#.#:&+:

```

Other solutions include `:.5#.#:+:`, `.5#.-:&#:`, and `:.5#.-:#:`
Try it!

# Explained

```
       #: Convert to base 2
      &   After
    +:    Doubling the input
  #.      Then convert to base 10 from base
.5        1/2

```
> 1 votes

# Answer
# APL+WIN, 16 bytes

Prompts for nth term 0 indexed. Uses the binary/base 0.5 approach.

```
.5⊥((n⍴2)⊤n←⎕),0

```

Try it online! Thanks to Dyalog Classic
> 1 votes

---
Tags: code-golf, sequence, rational-numbers
---


title: Can I wall glitch to there?

text:
# Question
Title: Can I wall glitch to there?
# Background

In a 2d game that I play, each screen is a 2d grid of tiles with walls and walkable tiles, with the player only able to travel on walkable tiles, and being stopped by walls. When the player walks past the edge of the screen, he will travel to the adjacent screen on the map, with the player's relative screen location on the opposite side of the edge he entered in the previous screen (Think about it this way: when he walks left to another screen, it makes sense that he will be on the right of next screen).

There is a glitch that you can perform that will allow the player to glitch into a wall and, in certain cases, clip out of the map. After that, the player can travel through walls. Since the player is out of the map, if he travels past any edge of the screen, he will be warped to the other side relative to the screen, but the actual 2d grid will be the same (the game tries to determine where the player is to generate the new screen, but because he is out of bounds, it won't find a valid screen to generate, so the screen won't change). If the player travels out of a wall and into a walkable tile, he can't walk through walls until he is in a wall again. This rule also applies when the player warps to the other side of the screen after he travels through an edge; if he warps from a wall to a walkable tile, he will not be able to go through walls. On the flip side, if the player warps from a walkable tile to a wall, he will clip into the wall and be able to go through walls again.

A side effect of this glitch is that the player's actual coordinates in the game map will change based on which edge he travels through. When the player travels through the top or bottom edge, his y-coordinate will increase or decrease by 1 respectively. Similarly, when the player travels through the left or right edge, his x-coordinate will decrease or increase by 1 respectively.

# Challenge

Given a configuration of walls and walkable tiles of the screen, is it possible for the player to reach a certain map coordinate? Assume that the player is always out of bounds (so the screen configuration always stays the same), and that the player starts at map coordinates `(0,0)`. You can place the initial position of the player relative to the screen anywhere you want (you can place the player in a wall or a walkable tile). You can also optionally take in the dimensions, `n` by `m`, of the screen.

# Example

Let's say the screen is 3 by 4 has the following configuration (`1` represent walls, `0` represent walkable tiles):

```
1 0 0 1
1 0 0 1
1 0 0 1

```

Can the player get to the coordinates `(-2,0)`? Let's start by placing the player on one of the walkable tiles. I will denote the player with a letter `P`:

```
1 0 0 1
1 0 P 1
1 0 0 1

```

Because there are two columns of walls lining the left and right edge of the screen, the player cannot access those two edges. Therefore, he can only go through the top and bottom edge. In other words, the y-coordinate can change, but the x-coordinate stays the same. The same goes for any other walkable tile on the screen. So `(-2,0)` can't be reached by placing the player on a walkable tile. But what if you place the player on one of the walls; for example, one of the left ones?

```
1 0 0 1
P 0 0 1
1 0 0 1

```

First, if the player travels to the right, he will pop out of the wall, resulting in the situation described above. In this case, the player can travel through the left edge to get to `(-1,0)`, but he will be warped to the right side of the screen:

```
1 0 0 1
1 0 0 P
1 0 0 1

```

The player is now at `(-1,0)`, but the goal is to get to `(-2,0)` ! The player has to go through the left edge again, but it can't be reached. If the player walks to the left onto the walkable tile, he will pop out of the wall and won't be able to warp back into the wall again. Going through the top or bottom edge won't help, because the player will still be in the walls on the right side, which is not connected to the left side. Travelling through the right edge will warp the player back to the left walls, but at the same time, it will increase his x-coordinate by 1, bringing the player back to `(0,0)`.

Lastly, if you place the player on one of the right walls, like so:

```
1 0 0 P
1 0 0 1
1 0 0 1

```

You will find that reaching `(-2,0)` is still impossible. Using a similar reasoning as above, you can determine that in order for the player to access the left edge to get closer to `(-2,0)`, the player will first have to travel to the right. That will give him access to the left edge, but that will increase his x-coordinate by 1, so his coordinates are now `(1,0)`. Now, travelling through the left edge as we intended initially will bring the player back to `(0,0)`, instead of `(-1,0)` like we wanted. Popping out of the wall at the start by going to the left is also not an option, because it will result in the first situation described above.

So, it is impossible to reach `(-2,0)` with the above screen configuration.

# Input

Your code should take in a rectangular 2d list (or any representation of a 2d grid) of two distinct characters or numbers, one representing walls and the other representing walkable tiles, for the screen configuration. It should also take in a coordinate pair with integer coordinates. Your code can optionally take in the dimensions `n` and `m`.

# Scoring

This is , so the shortest code in byte count wins!

# Test Cases

Uses `0` for walkable tiles and `1` for walls. The 2d ascii grid above each test case is just for reference.

```
n, m, coordinates, configuration
--> Output

False Cases
------------
1 0 0 1
1 0 0 1
1 0 0 1

3, 4, (-2, 0), [[1, 0, 0, 1], [1, 0, 0, 1], [1, 0, 0, 1]]
--> False

1 0 1
0 1 0
1 0 1

3, 3, (0, 2), [[1, 0, 1], [0, 1, 0], [1, 0, 1]]
--> False

1 0 1 1 1 1 1 1 1
1 1 0 0 0 1 0 1 1
1 1 1 0 1 0 1 0 1
0 1 0 1 1 1 1 1 0
1 0 1 1 1 1 1 1 1

5, 9, (2, 2), [[1, 0, 1, 1, 1, 1, 1, 1, 1], [1, 1, 0, 0, 0, 1, 0, 1, 1], [1, 1, 1, 0, 1, 0, 1, 0, 1], [0, 1, 0, 1, 1, 1, 1, 1, 0], [1, 0, 1, 1, 1, 1, 1, 1, 1]]
--> False

1 0 0 0 1 0 0 0 1 0 0 0 1
0 1 1 1 0 1 1 1 0 1 1 1 0
0 1 1 1 1 0 1 1 1 1 1 1 0
1 1 1 1 1 1 0 1 1 1 1 1 1
1 1 0 1 1 1 0 1 1 1 0 1 1
0 0 1 0 0 0 1 0 0 0 1 0 0

6, 13, (-200, 100), [[1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1], [0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0], [0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1], [1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1], [0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0]]
--> False

True Cases
------------
0 0 0 1
1 0 0 1
1 0 0 1

3, 4, (-2, -2), [[0, 0, 0, 1], [1, 0, 0, 1], [1, 0, 0, 1]]
--> True

1 1 1 1
1 0 0 0
1 0 0 0
1 0 0 0

4, 4, (100, 100), [[1, 1, 1, 1], [1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0]]
--> True

0 0 1 0 0
0 0 1 0 0
1 1 1 1 1
0 0 1 0 0
0 0 1 0 0

5, 5, (1, -1), [[0, 0, 1, 0, 0], [0, 0, 1, 0, 0], [1, 1, 1, 1, 1], [0, 0, 1, 0, 0], [0, 0, 1, 0, 0]]
--> True

0 0 1 0 0
1 1 1 0 0
0 0 1 1 1
0 0 1 0 0

4, 5, (-123, 456) [[0, 0, 1, 0, 0], [1, 1, 1, 0, 0], [0, 0, 1, 1, 1], [0, 0, 1, 0, 0]]
--> True

1 0 0 0 1 0 0 0 1 0 1 1 0
0 1 1 1 0 1 1 1 0 1 0 0 1
1 1 1 1 1 0 1 1 1 1 1 1 0
1 1 1 1 1 1 0 1 1 1 1 1 0
1 1 0 1 1 1 0 1 1 1 1 1 0
0 0 1 0 0 0 1 0 0 0 1 0 0

6, 13, (-200, 100), [[1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0], [0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0, 1], [1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0], [1, 1, 0, 1, 1, 1, 0, 1, 1, ,1 ,1 ,1 ,0], [0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0]]
--> True

```

# Answer
> 5 votes
# Python3, 975 bytes:

```
E=enumerate
def S(b,x,y):
 q=[(x,y,0,0,b[x][y],[(x,y)])]
 while q:
  n,m,j,k,t,p=q.pop(0)
  for X,Y in[(1,0),(-1,0),(0,1),(0,-1)]:
   N=n+X;M=m+Y;F=0;J=j;K=k
   if N<0 or M<0:J,K=j+(N<0),k-(M<0);yield J,K,0;N=len(b)-1 if N<0 else N;M=len(b[0])-1 if Y<0 else M;F=1
   elif N>=len(b)or M>=len(b[0]):J,K=j-(N>=len(b)),k+(M>=len(b[0]));yield J,K,0;N=0 if N>=len(b)else N;M=0 if M>=len(b[0])else M;F=1
   if(N,M)==(x,y)and(b[N][M]==0 or t):yield J,K,1,p
   elif(N,M)not in p:
    if F or b[N][M]==0 or t:q+=[(N,M,*([0,0]if b[N][M]==0 and t and F==0 else [J,K]),b[N][M],p+[(N,M)])]
def V(g,h,G,H):
 r=[]
 if g==0:r+=[G==0]
 else:r+=([(g<0)==(G<0),g%G==0]if G else[0])
 if h==0:r+=[H==0]
 else:r+=([(h<0)==(H<0),h%H==0]if H else[0])
 return all(r)
def f(t,b):
 for x,a in E(b):
  for y,_ in E(a):
   K={0:set(),1:set()}
   for z,v,F,*_ in S(b,x,y):
    if(v,z)==t and not F:return 1
    if F:K[0].add(v);K[1].add(z)
   if any(V(*t,G,H)for G in K[0] for H in K[1]):return 1
 return 0

```

Try it online!

---
Tags: code-golf, array, decision-problem, grid
---


title: Number of rotations

text:
# Question
Title: Number of rotations
### Task

Write a function or a program to find the number of rotations required by a wheel to travel a given distance, given its radius.

### Rules

Input can be 2 positive rational numbers and can be taken in any convenient format.

Both inputs are of same unit.

**There must not be any digits 0-9 in your code.**

The output will be an integer (in case of float, round to infinity)

This is **code-golf** so shortest code wins

### Examples

```
distance radius  output
10       1       2
50       2       4
52.22    4       3
3.4      0.08    7
12.5663  0.9999  3

```

# Answer
# MathGolf, ~~5~~ 4 bytes

```
τ/╠ü

```

Try it online!

## Explanation

```
τ      Push tau (2*pi)
 /     Divide the first argument (total distance) by tau
  ╠    Reverse divide (computes (distance/tau)/radius)
   ü   Ceiling

```
> 6 votes

# Answer
# Java 8, ~~32~~ 30 bytes

```
a->b->-~(int)(a/b/Math.PI/'')

```

Contains unprintable `\u0002` between the single quotes.

Port of *@jOKing*'s Perl 6 answer.

Try it online.
> 4 votes

# Answer
# Perl 6, ~~15~~ 12 bytes

*-3 bytes tjanks to nwellnhof reminding me about tau*

```
*/*/τ+|$+!$

```

Try it online!

Anonymous Whatever lambda that uses the formula `(a/b/tau).floor+1`. Tau is two times pi. The two anonymous variables `$` are coerced to the number `0`, which is used to floor the number `+|0` (bitwise or 0) and add one `+!$` (plus not zero).
> 4 votes

# Answer
# APL+WIN, 9 bytes

Prompts for radius followed by distance:

```
⌈⎕÷○r+r←⎕

```

Try it online! Courtesy of Dyalog Classic

Explanation:

```
○r+r←⎕ prompt for radius and double it and multiply by pie

⌈⎕÷ prompt for distance, divide by result above and take ceiling

```
> 4 votes

# Answer
# Python 2, ~~47~~ ~~45~~ ~~44~~ 43 bytes

```
lambda l,r:l/(r+r)//math.pi+l/l
import math

```

Try it online!

---

* -2 bytes, thanks to flawr
* -1 byte, thanks to Jonathan Allan
> 3 votes

# Answer
# 05AB1E, 6 bytes

```
·/žq/î

```

Port of *@flawr*'s Python 2 comment.
Takes the input in the order `radius`,`distance`.

Try it online or verify all test cases.

**Explanation:**

```
·         # Double the first (implicit) input
 /        # Divide the second (implicit) input by it
  žq/     # Divide it by PI
     î    # Ceil it (and output implicitly)

```
> 2 votes

# Answer
# MathGolf, ~~6~~ 5 bytes

```
∞/π/ü

```

Semi-port of *@flawr*'s Python 2 comment.
Takes the input in the order `radius distance`.

-1 byte because `ceil` builtin has just been added, replacing the `floor+1`.

Try it online.

**Explanation:**

```
∞        # Double the first (implicit) input
 /       # Divide the second (implicit) input by it
  π/     # Divide it by PI
    ü    # Ceil (and output implicitly)

```
> 2 votes

# Answer
# PHP, 47 bytes

```
<?=ceil($argv[++$i]/M_PI/(($b=end($argv))+$b));

```

Try it online.
> 2 votes

# Answer
# Ruby, 29 bytes

```
->l,r{(l/Math::PI/r+=r).ceil}

```

Try it online!
> 2 votes

# Answer
# Catholicon, 8 bytes

```
ċ//ĊǓĊ`Ė

```

Explanation:

```
  /ĊǓĊ    divide the first input by the doubled second input
 /    `Ė  divide that by pi
ċ         ceil

```

New version (pi builtin made one byte, division parameters swapped), 5 bytes

```
ċ/π/Ǔ

```
> 2 votes

# Answer
## **C, 46 bytes**

```
f(float a,float b){return ceil(a/(b+b)/M_PI);}

```

I'm new to PPCG, so I'm not sure wether I have to count other parts in the byte count, such as the

```
include <math.h>

```

needed for the ceil function, which will rise the count to **64 bytes**
> 2 votes

# Answer
# , 10 9 bytes

```
>.@%o.@+:

```

Try it online!
> 2 votes

# Answer
# Stax, 5 bytes

```
Vt*/e

```

Run and debug it

```
Vt*   multiply by tau (2pi)
/     divide
e     ceiling

```
> 2 votes

# Answer
# C (gcc), ~~45~~ ~~47~~ 45 bytes

```
f(d,r,R)float d,r;{R=ceil(d/r/'G'/'\n'*'q');}

```

A reasonable approximation of pi is 355/113. Since circumference C = 2 * r * PI, we can instead of pi use tau, which is then of course ~710/113. 710 happens to have the convenient factors 2 * 5 * 71, which is compactly expressed as `'G' * '\n'`. ~~We add one (`r/r`) to force rounding to infinity.~~

Edit: My trick was too clever for its own good: it of course made it fail if the distance was a multiple of the circumference.

Try it online!
> 2 votes

# Answer
# Julia 1.0, 20 bytes

```
f(d,r)=cld(d/π,r+r)

```

Try it online!
> 2 votes

# Answer
# , ~~39~~ 32 bytes

-7 bytes Thanks to Giuseppe

```
function(d,r)ceiling(d/(r+r)/pi)

```

Try it online!

I feel like this could definitely be golfed, but I am a bit lazy right now to do anything about it
> 2 votes

# Answer
# min, 16 bytes

```
/ tau / ceil int

```

Takes the distance and radius put on the stack in that order. Then divides by tau, rounds, and makes int.
> 2 votes

# Answer
# JavaScript (Babel Node), 25 bytes

*-2 bytes using @flawr comment =D. -1 from @Kevin. -7 from @Shaggy*

```
a=>b=>-~(a/(b+b)/Math.PI)

```

Try it online!
> 1 votes

# Answer
# Jelly, 6 bytes

```
÷÷ØPHĊ

```

Try it online!
> 1 votes

# Answer
# Lua, 61 58 57 49 bytes

```
function(s,r)return math.ceil(s/(r+r)/math.pi)end

```

Try it online!

*Thanks to KirillL. -8 bytes.*
> 1 votes

# Answer
# Japt, 7 bytes

```
/MT/V c

```

Try it here
> 1 votes

# Answer
# Dart, ~~47~~ 46 bytes

```
import'dart:math';f(a,b)=>(a/(b+b)/pi).ceil();

```

Try it online!

* -1 byte thanks to @Shaggy
> 1 votes

# Answer
**Haskell, 25 bytes**

```
f d r=ceiling(d/(r+r)/pi)

```
> 1 votes

# Answer
# Common Lisp, 36 bytes

```
(lambda(a b)(ceiling(/ a(+ b b)pi)))

```

Try it online!
> 1 votes

# Answer
# Tcl, 50 bytes

```
proc N d\ r {expr ceil($d/(($r+$r)*acos(-$r/$r)))}

```

Try it online!

---

~~Tcl, 53 bytes
```
proc N d\ r {expr ceil($d/(($r+$r)*acos(-[incr i])))}

```
Try it online!<br>~~

Lack of a pi constant or function makes me lose the golf competition!
> 1 votes

# Answer
# PowerShell, 53 52 51 bytes

-1 byte thanks to @mazzy
-1 byte after I realized I don't need a semicolon after the `param()` block

```
param($d,$r)($a=[math])::ceiling($d/($r+$r)/$a::pi)

```

Try it online!

Takes input from two commandline parameters, distance `-d` and radius `-r`.
> 1 votes

# Answer
# Pari/GP, ~~23~~ 19 bytes

```
(d,r)->-d/(r+r)\-Pi

```

Try it online!
> 1 votes

# Answer
# Desmos, 22 bytes

```
f(d,r)=ceil(d/π(r+r))

```

Try it on Desmos!
> 1 votes

# Answer
# JavaScript (Babel Node), 23 bytes

```
s=>r=>-~(s/2/r/Math.PI)

```

Try it online!
> 0 votes

# Answer
# Clojure, 50 bytes

```
(fn[a b](int(Math/ceil(/ a Math/PI(count"  ")b))))

```

An anonymous function that accepts two integers `a` and `b` as arguments: the distance and the wheel's radius, respectively.

Try it online!

`(count " ")` evaluates to `2`, so this function implements \\$\lceil \dfrac a{2\pi b} \rceil\\$.
> 0 votes

# Answer
# TI-Basic (83 series), 12 bytes

```
-int(-Tmax⁻¹min(e^(ΔList(ln(Ans

```

Takes input as a list of radius and distance in `Ans`: for example, `{0.9999:12.5663:prgmX`.

`e^(ΔList(ln(Ans` will take the ratio of those distances, and `min(` turns this into a number. Then we divide by `Tmax`, which is a graphing parameter that's equal to 2π by default. Finally, `-int(-` takes the ceiling.
> 0 votes

# Answer
# SmileBASIC, 28 bytes

```
INPUT D,R?CEIL(D/(R+R)/PI())

```
> 0 votes

# Answer
# Intel 8087 FPU assembly, 22 bytes

```
; input: D,R (shortreal,shortreal)
; output: O (memsixteen)
FDIST   MACRO  D, R, O
    FLD  D      ; ST[] = D
    FLDPI       ; ST[] = PI
    FDIV        ; ST = D / PI
    FLD  R      ; ST[] = R
    FLD  ST     ; ST[] = R
    FADD        ; ST = R + R
    FDIV        ; ST = D / PI / R + R
    FISTP O
        ENDM

```

Uses only the Intel Eighty-Eighty-Seven math-coprocessor. Inputs Distance (D) and Radius (R) as thirty-two bit IEEE Seven-Fifty-Four single-precision real. Returns O as a sixteen bit unsigned int.
> 0 votes

# Answer
# Ruby, 31 bytes

```
->d,r{d/=Math::PI*(r+r);d.ceil}

```

Try it online!
> 0 votes

# Answer
# Factor \+ `cursors`, 18 bytes

```
[ / pi pi + up/i ]

```

Try it online!

Divide the distance by the radius, then ceiling-integer-divide that by 2pi. The ceiling-integer-division word `up/i` is provided by the `cursors` vocabulary.
> 0 votes

---
Tags: code-golf, restricted-source
---