Tell me more ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Recreate '99 bottles of beers on the wall'.

The desired output is this:

99 bottles of beer on the wall, 99 bottles of beer.
Take one down and pass it around, 98 bottles of beer on the wall.

98 bottles of beer on the wall, 98 bottles of beer.
Take one down and pass it around, 97 bottles of beer on the wall.

97 bottles of beer on the wall, 97 bottles of beer.
Take one down and pass it around, 96 bottles of beer on the wall.

96 bottles of beer on the wall, 96 bottles of beer.
Take one down and pass it around, 95 bottles of beer on the wall.

95 bottles of beer on the wall, 95 bottles of beer.
Take one down and pass it around, 94 bottles of beer on the wall.

....

3 bottles of beer on the wall, 3 bottles of beer.
Take one down and pass it around, 2 bottles of beer on the wall.

2 bottles of beer on the wall, 2 bottles of beer.
Take one down and pass it around, 1 bottle of beer on the wall.

1 bottle of beer on the wall, 1 bottle of beer.
Go to the store and buy some more, 99 bottles of beer on the wall.

Show me how you would solve this with your favorite programming language. Most creative use of a language wins.

share|improve this question
17  
"Most creative use" is too subjective for an SE site, I think. We should aim to use objective criteria, such as "shortest code". – Chris Jester-Young Jan 27 '11 at 21:04
4  
Still a good question though – SimpleCoder Jan 27 '11 at 21:06
1  
Is it supposed to run infinitely? I assumed so. Also codegolf doesn't own 99 bottles of beer so there is not reason to even discuss it. – Mike Bethany Jan 28 '11 at 8:04
1  
@Chris -- That is going to be the toughest part of this SE site, because the whole thing is based on creativity, because that is half the fun of programming puzzles. The most creative solution isn't always the most efficient or shortest. – Nick Berardi Jan 28 '11 at 14:13
2  
@Nick: I hear you. I just want to know how one can determine how creative a solution is---based on your own judgement? Based on the voters'? Neither is particularly reliable (no offence). Something like brevity is indisputable---for example, nobody can dispute the "goodness" of the 1-byte stack overflow code golf solution. – Chris Jester-Young Jan 28 '11 at 14:26
show 4 more comments

80 Answers

1 2 3
up vote 39 down vote accepted

Perl (410 characters)

There's already a website dedicated to this contest:

One of the Perl solutions would be very very hard to beat in terms of creativity, it reads:

[bottles.pl]


         $a=
        "cpuu
       \bmft p
       \bg cff
       \bs";$b
       ="po ui
       \bf xbm
      \bm";$c="
      Ypv ublf p
     \bof epxo qb
   \btt ju bspvoe";
  $a =~ s/\n//;$a =~
  s/\s+/ /g; $b   =~
  s/\n// ;  $b    =~
  s/\s+/ /g;$c    =~
  s/\n// ;  $c    =~
  s/\s+/ /g;$a    =~
  y/b-z/a-z/;$b   =~
  tr/b-z/a-z/;$c  =~
  tr/b-z/a-z/ ; for(
  $d=100;$d>0;$d--){
  print"$d $a $b $d"
  ;print" $a,\n$c, "
  ;print($d-1);print
  " $a $b.\n";} $x =
  "cjc"; $y="dobbz";
  $z="com";print"\n"
  ;print "- $x\@$y."
   ;print"$z \n\n";

Here's the link to the original file.

share|improve this answer

Brainf*** (1,509)

I figured I could trump this answer by not only making 9 beer bottles instead of 1, but also by only using 7 different characters in the code.

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

I do have to admit though, there is a bug in the code (maybe you can figure out how to fix it for me?) and it does not print the final sentence, Go to the store and buy some more, 99 bottles of beer on the wall. But other than that, it functions just as well as any of the programs made in those sissy programming languages everyone else seems to like to use.

share|improve this answer
6  
+1 for the ASCII art within the code – Nate Koppenhaver Apr 27 '11 at 18:14
3  
+1 for the effort. – Chris Apr 29 '11 at 8:47
show 1 more comment

Funciton

I wrote this just the other day. :) (Screenshots: start and finish)

                                            ╓┬────╖
     ╔════╗  ┌───╖                          ╟┘99b ║
     ║ −1 ╟──┤ + ╟──┐                       ╙──┬──╜
     ╚════╝  ╘═╤═╝  ├──────────────────────────┴─────────────────────────────┐
     ╔════╗  ┌─┴─╖  │  ╔════════════════════════════════════════════════════╗│
     ║ 99 ╟──┤ ? ╟──┘  ║ 93438979891487426396059469986395555362079573844971 ║│
     ╚════╝  ╘═╤═╝     ║ 71377306928718494179034460561943201885027745835961 ║│
            ┌──┴───╖   ║ 98129935108241412387473531261660077880505710501626 ║│
    ╔════╗  │ 99bp ║   ║ 32694396343717333192558234646820019070451056711    ║│
    ║ 99 ║  ╘══╤═══╝   ╚══════════════════════════╤═════════════════════════╝│
    ╚═╤══╝   ┌─┴─╖                       ┌───╖  ┌─┴─╖  ╔═════════════════╗   │
   ┌──┴──╖   │ ‼ ╟───────────────────────┤ ‼ ╟──┤ ? ╟──╢ 445551776368547 ║   │
   │ 99b ║   ╘═╤═╝┌─────────────────────┐╘═╤═╝  ╘═╤═╝  ║ 925186328623383 ║   │
   ╘══╤══╝     │  │╔═══════════════════╗│  │      │    ║ 851314944882510 ║   │
      │        │  │║ 15177132563375318 ║│  │      │    ║ 812246570019017 ║   │
 ╔════════╗    │  │║ 07655616350359109 ║│  │      │    ║ 240477365113929 ║   │
 ║ 318287 ║    │  │║ 82597577171382437 ║│  │      │    ║ 659548419629671 ║   │
 ║ 023073 ║    │  │║ 18150105146396039 ║│  │      │    ║ 952755268258505 ║   │
 ║ 603558 ║    │  │║ 2022986808360992  ║│  │      │    ║ 759402210908648 ║   │
 ║ 743780 ║    │  │╚══════════╤════════╝│  │      │    ║ 737406010882693 ║   │
 ║ 068900 ║    │  │         ┌─┴─╖ ┌───╖ │  │      │    ║ 018745757193818 ║   │
 ║ 028319 ║    │  │         │ ‼ ╟─┤ ‼ ╟─┘  │      │    ║ 597439618635403 ║   │
 ║ 948400 ║    │  │         ╘═╤═╝ ╘═╤═╝    │      │    ║ 821854707881243 ║   │
 ║ 620075 ║    │  │         ┌─┴─╖   │    ┌─┴─╖    │    ║ 92049082452     ║   │
 ║ 955580 ║    │  └─────┬───┤ ‼ ╟────────┤ ‼ ║    │    ╚═════════════════╝   │
 ║ 347161 ║    │        │   ╘═══╝┌──────┐╘═╤═╝    └─────────────┐            │
 ║ 651333 ║    │   ╔═══╗│┌──────╖│╔════╗│ ╔╧═════════╗          │            │
 ║ 590970 ║    │   ║ 0 ║└┤ 99bp ╟┘║ −1 ║└┐║ 20971566 ║          ├────────────┘
 ║ 678045 ║    │   ╚══╤╝ ╘══════╝ ╚══╤═╝ │╚══════════╝          │
 ║ 336290 ║  ┌─┴─╖  ┌─┴─╖  ┌─────╖  ┌┴──╖├──────────────────────┘
 ║ 721824 ╟──┤ ‼ ╟──┤ ? ╟──┤ 99b ╟──┤ + ║│
 ╚════════╝  ╘═══╝  ╘═╤═╝  ╘═════╝  ╘═╤═╝│    ╓┬──────╖
                      └───────┬───────┘  │    ╟┘ 99bp ║
                              └──────────┘    ╙───┬───╜
 ┌────────────────────────────────────────────────┴──────────────┐
 │╔══════════════════════════════════════════╗╔═══════════╗      │
 │║ 8592134145756414358602136806465202028576 ║║ 232783950 ║      │
 │╚══════════════════════════════╤═══════════╝╚╤══════════╝      │
 │               ┌───╖  ╔═══╗  ┌─┴─╖  ┌───╖  ┌─┴─╖  ┌─────────╖  │
 └───────────────┤ = ╟──╢ 1 ║  │ ‼ ╟──┤ ‼ ╟──┤ ? ╟──┤ int→str ╟──┴┐
                 ╘═╤═╝  ╚═══╝  ╘═╤═╝  ╘═╤═╝  ╘═╤═╝  ╘═════════╝   │
          ╔═══╗  ┌─┴─╖         ┌─┴─╖    │      └──────────────────┘
          ║ 0 ╟──┤ ? ╟─────────┤ ‼ ╟──┐
          ╚═══╝  ╘═╤═╝         ╘═══╝  │
              ╔════╧╗╔════════════════╧════════════════════════════════╗
              ║ 115 ║║ 20338288213193790107412311132593873016630280224 ║
              ╚═════╝╚═════════════════════════════════════════════════╝
share|improve this answer
show 3 more comments

jQuery + FireBug Console

$('code:first').text()

;)

share|improve this answer
5  
+1: Very creative! – Timwi Jul 14 '11 at 15:08
1  
What about something like eval($($('code')[8]).text().replace(/print/g,'console.log')) <del>(aka. stealing)</del>? It prints the whole lyrics of the song. :P – JiminP Jul 26 '11 at 8:59
1  
Also works on Chrome's javascript console. – Spoike Sep 22 '11 at 8:08
show 1 more comment

Who said C# had too much ceremony? Whoever it was, they have never been so right.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace _99Bottles
{
    class Program
    {
        static void Main(string[] args)
        {
            PrintSong(99);
        }

        static void PrintSong(int bottleCount)
        {
            Func<int, string> sOrBlank = howMany => howMany > 1 ? "s" : "";

            PrintBottles(howManyBottles =>
            {
                Console.WriteLine("{0} bottle{1} of beer on the wall, {0} bottle{1} of beer.", howManyBottles, sOrBlank(howManyBottles));
                if (howManyBottles > 1)
                {
                    Console.WriteLine("Take one down and pass it around, {0} bottle{1} of beer on the wall.", --howManyBottles, sOrBlank(howManyBottles));
                }
                else
                {
                    Console.WriteLine("Go to the store and buy some more, 99 bottles of beer on the wall.", --howManyBottles);
                }
            },
            bottleCount);
        }

        static void PrintBottles(Action<int> printBottles, int count)
        {
            printBottles(count);

            if (count > 1)
            {
                PrintBottles(printBottles, --count);
            }
         }
    }
}
share|improve this answer
9  
+1 For being another C-style sacrificial lamb in an ocean of Perl. – Glenn Nelson Jan 27 '11 at 21:26
2  
@Nellius Did you even read what ilivewithian said before his code? – Daniel Standage Jan 28 '11 at 14:08
1  
@Daniel Yes, and it implies that he thinks everything in his code is necessary. If meant as a joke, it shouldn't be voted up this much. It's not short, creative, efficient, or even slightly clever. – Nellius Jan 28 '11 at 14:16
show 2 more comments

HQ9+ (1 character)

9

Admittedly its not a Turing complete language, but this still counts

share|improve this answer
12  
Then don't come here. I don't go to Justin Bieber concerts just so I can interrupt your soulful dancing to tell you how much he sucks. – Mike Bethany Jan 28 '11 at 9:24
6  
Why don't you use HQ9 B? It's Turing complete. – muntoo Apr 30 '11 at 5:25
show 1 more comment

Definitely doesn't qualify as creative, but it gets'r done from the command line with a single command.

perl -e '$i=99;while($i>1){print("$i bottles of beer on the wall, $i bottles of beer.\nTake one down and pass it around, ".--$i." bottles of beer on the wall\n\n");}print("1 bottle of beer on the wall, 1 bottle of beer.\nGo to the store and buy some more, 99 bottles of beer on the wall.\n");'
share|improve this answer

Curl 19 characters

(requires internet connection)

curl -L j.mp/eGv9K5
share|improve this answer
5  
I consider this stretching it too far. – marcog Jan 28 '11 at 11:24
6  
I consider it a joke. Many solutions can be hidden behind a query to a web server. – Alexandru Jan 28 '11 at 15:48
2  
I like this one nevertheless. – pimvdb May 31 '11 at 19:53
1  
If objective was shortest code, I'd give you a point for cleverness. – Neil Jul 7 '11 at 14:15

C# (312 310 304 characters)

class P{static void Main(){string b=" bottle",w=" on the wall",o=" of beer",p=".\n",s="s";for(int i=99;i>0;i--)System.Console.Write(i+b+(i>1?s:"")+o+w+", "+i+b+(i>1?s:"")+o+p+(i>1?"Take one down and pass it around, "+(i-1)+b+(i-1>1?s:"")+o+w+p+"\n":"Go to the store and buy some more, "+99+b+s+o+w+p));}}
share|improve this answer
1  
I can't believe you got it in shorter than me. I'm impressed. I'll have to study for a better set of options – jcolebrand Jan 29 '11 at 6:30
show 1 more comment

Windows PowerShell (186)

filter b{"$_ bottle$('s'*!!--$_) of beer"}(99..1|%{($_|b)+" on the wall, $($_|b)."
"Take one down and pass it around, $(--$_|b).
"})[0..196]
"Go to the store and buy some more, $(99|b)."

Fairly straightforward.

I'm using a filter for the bottles of beer, since function is longer and invocation needs parentheses in any case. The plural detection (!!--$_) first decrements the number of bottles by one (so plural is anything non-zero), casts it to boolean and negates it with the first ! and negates it again so we now have a boolean describing whether the number needs a plural or not. This is then implicitly casted to an integer when multiplying the string.

Inline line breaks are fun.

Spawning more lines than needed and cutting back afterwards, too.

share|improve this answer
show 1 more comment

Haskell, 272, 250, 243 characters

(&)=(++)
b 1=" bottle"
b _=b 1&"s"
w=" on the wall"
p n=show n&b n&" of beer"
f n=putStrLn$p n&w&","&p n&".\n"&c(n-1)
c 0="Go to the store and buy some more, "&p 99&w&"."
c n="Take one down and pass it around, "&p n&w&"\n"
main=mapM f[99,98..1]
share|improve this answer

Almost-correct anti-golf from the uber-eager new C programmer who's learning Perl?

#!/usr/bin/perl
#      ^
#      |
#      |
# That's the Perl interpreter.
# You might need to change this line based on
# your Linux/Unix distribution.

# Pragmas for debugging!
use strict;
use warnings;

# Library dependencies...none! lolz

# Main implementation
my $number_of_bottles_of_beer_on_the_wall = 99; #start with 99 bottles
LOOP: while( $number_of_bottles_of_beer_on_the_wall > 0 )
{
  printf( "%d bottles of beer on the wall, %d bottles of beer\n",
          $number_of_bottles_of_beer_on_the_wall,
          $number_of_bottles_of_beer_on_the_wall,                  );

  if( $number_of_bottles_of_beer_on_the_wall > 1 )
  {
    $number_of_bottles_of_beer_on_the_wall -= 1;
    printf( "Take one down and pass it around, %d bottles of beer on the wall.\n\n",
            $number_of_bottles_of_beer_on_the_wall,                               );
  }
  else
  {
    printf( "Go to the store and buy some more, %d bottles of beer on the wall\n",
            99                                                                     );
    last LOOP;
  }
}
share|improve this answer

Javascript (285)

This assumes there is a function called print, to output a string.

b=' of beer on the wall';n=100;while(--n>1)if(n>1)print(n+" bottles"+b+', '+n+" bottles of beer.\nTake one down and pass it around, "+(n-1)+' bottle'+(n-1>1?'s':'')+b+'.\n\n');print("1 bottle"+b+", 1 bottle of beer.\nGo to the store and buy some more, 99 bottles of beer on the wall.")
share|improve this answer
7  
I'm not sure that assumed functions are fair. For example, my program could be b();. Assuming there is a function b() that prints 99 bottles of beer on the wall. :) – SimpleCoder Jan 27 '11 at 21:37
9  
Javascript doesn't provide any standard way to output a string, if you are running it in a browser, it doesn't have a print function, if you are running it in rhino, you do. – user11 Jan 27 '11 at 21:39
2  
document.writeln works. – SimpleCoder Jan 27 '11 at 21:44
3  
... for browsers – user11 Jan 27 '11 at 21:50
3  
JavaScript has IO with: alert as output, prompt as variable input and confirm as boolean input. They suck as far as UI goes, but they are the standard blocking IO functions. alert and print are the same length, so your code should be about equal. – zzzzBov May 14 '11 at 20:09
show 4 more comments

PHP: 285 240 233 231 Characters

$i=99;$b=" bottles of beer";$o=" bottle of beer";$c=" on the wall";while($i>1){echo"$i$b$c, $i$b.\nTake one down and pass it around, ".--$i.(($i>1)?$b:$o).$c.".\n\n";}echo"$i$o$c, $i$o.\nGo to the store and buy some more, 99$b$c.";

Output here: http://ideone.com/jhyER

share|improve this answer

JavaScript (216 228 215)

for(a=99,c=" on the wall";a;)document.write((d=eval(b="(a||99)+' bottle'+(a-1?'s':'')+' of beer'"))+c+", "+d+".<br>"+(--a?"Take one down and pass it around, ":"Go to the store and buy some more, ")+eval(b)+c+".<p>")

Edit: Had a single "1 bottles of beer" in initial version, 3rd version is completely rewritten, notice cool tricks like (a||99) to get 99 in the last line, (a-1?'s':'') making plural for every case but a==1 though without need for the wasteful ==, and setting the value of b inside a statement where it is used.

share|improve this answer
show 2 more comments

C

This program is generating the complete song text as single string using the preprocessor. The actual C code just outputs the string thus constructed. Calling strings on the generated executable will reveal the complete song text in the executable.

#define BOTTLES(n) n " bottles of beer"
#define BOTTLE "1 bottle of beer"
#define OTW " on the wall, "
#define TAKE "Take one down, pass it around, "
#define BUY "Go to the store and buy some more, "
#define STOP "."
#define NL "\n"

#define LINE1(n) BOTTLES(n) OTW BOTTLES(n) STOP NL
#define LINE1A BOTTLE OTW BOTTLE STOP NL
#define LINE2(n) TAKE BOTTLES(n) STOP NL
#define LINE2A TAKE BOTTLE STOP NL
#define LINEX BUY BOTTLES("99") NL

#define MIDDLEPART(n) LINE2(n) NL LINE1(n)
#define MIDDLELAST LINE2A NL LINE1A

#define EIGHT_TO_TWO(S, M) M(S "8") M(S "7") M(S "6") M(S "5") M(S "4") M(S "3") M(S "2")
#define EIGHT_TO_ONE(S, M) EIGHT_TO_TWO(S, M) M(S "1")
#define EIGHT_TO_TWO_AGAIN(S, M) M(S "8") M(S "7") M(S "6") M(S "5") M(S "4") M(S "3") M(S "2")
#define EIGHT_TO_ONE_AGAIN(S, M) EIGHT_TO_TWO_AGAIN(S, M) M(S "1")
#define NINE_TO_TWO(S, M) M(S "9") EIGHT_TO_TWO(S, M)
#define EIGHT_TO_ZERO(S, M) EIGHT_TO_ONE(S, M) M(S "0")
#define NINE_TO_ZERO(S, M) M(S "9") EIGHT_TO_ZERO(S, M)

#define NINETIES EIGHT_TO_ZERO("9", MIDDLEPART)
#define NTIES(n) NINE_TO_ZERO(n, MIDDLEPART)
#define EIGHTIES_TO_TENS EIGHT_TO_ONE_AGAIN("", NTIES)
#define NAUGHTIES NINE_TO_TWO("", MIDDLEPART)

#define SONG LINE1("99") NINETIES EIGHTIES_TO_TENS NAUGHTIES MIDDLELAST LINEX

#include <stdio.h>

int main()
{
  puts(SONG);
  return 0;
}
share|improve this answer

Python, 241 chars

s=""
i=99
b="%d bottl%s of beer"
w=" on the wall"
t="Take one down and pass it around, "
p=q="es"
while i:s+=b%(i,p)+w+", "+b%(i,p)+".\n";i-=1;p=p[:i];s+=t+b%(i,p)+w+".\n\n"
print s[:-64]+"Go to the store and buy some more, "+b%(99,q)+w+"."
share|improve this answer

Ruby, 274 bytes

Still pretty new to Ruby, really just playing around

o =" bottles of beer";w=" on the wall";t="Take one down and pass it around, ";s=" bottle of beer"
99.downto(3){|b|puts"#{b}#{o+w}, #{b}#{o}.\n#{t}#{b-1}#{o+w}.\n\n"}
puts"2 #{o+w}, 2 #{o}.\n#{t}1#{s}#{w}.\n\n1#{s+w}, 1#{s}.\nGo to the store and buy some more, 99#{o+w}."
share|improve this answer

Scheme (270)

No whitespace:

(let l((i 99))(let((b" bottle")(c" on the wall")(d"Take one down and pass it around,")(e".\n")(f", ")(g" of beer"))(if(= i 1)(map display`(1,b,g,c,f,1,b,g,e"Go to the store and buy some more, 99",b,c,e))(begin(map display`(,i,b,g,c,f,i,b,e,d,i,b,c,e"\n"))(l(-1+ i))))))

With whitespace:

    (let l ((i 99))
      (let ((b" bottle")
            (c" on the wall")
            (d"Take one down and pass it around, ")
            (e".\n")
            (f", ")
            (g" of beer"))
        (if (= i 1)
            (map display`(1 ,b ,g ,c ,f ,1 ,b ,g ,e
                          "Go to the store and buy some more, 99" ,b ,c ,e))
            (begin (map display `(,i ,b ,g ,c ,f ,i ,b ,e ,d ,i ,b ,c ,e "\n"))
                   (l (-1+ i))))))
share|improve this answer
show 1 more comment

Python (318)

I found this way of making a Python program shorter :)

exec'eJxtjrFqwzAQQHd/xVVgLCVqSbq5RHO2TtlcgyX7Qk3luyAphP59ZA0thGzi9O7es0bUERyn5DE/+AwOMdTxi0TljLeLmyzQB4GlaaCBg/hkWDigqMb/76aZz0CHHaCPCLaWTpLSTWw2kl7MXmkBTJC+EW7Wey3U9hmzzqU42R/MNMLEt6KFi40R5gQ28JUmndO0ODIkLhdjyjWFc9dfiLxg6Vsx1ZExu36Vddn2miVD2w59R4d9/6d+f8h7Wze3Y+GrS5gpwSjbVlV3Y1BZCg=='.decode('base64').decode('zip')
share|improve this answer
show 2 more comments

C#

Not intended to be short, but perhaps this counts as creative?

using System;
using System.Linq;

class Program
{
    static void Main()
    {
        Console.WriteLine(string.Join(Environment.NewLine, Enumerable.Range(0, 100).Select(i =>
            string.Format(
                string.Format(
                    "{0} {1} {{3}} {{4}},{{9}}{0} {1} {{3}}.{{9}}{2},{{9}}{3} {4} {{3}} {{4}}.{{9}}",
                    i == 99 ? "{0}" : "{7}",
                    i == 98 ? "{1}" : "{2}",
                    i == 99 ? "{6}" : "{5}",
                    i == 98 ? "{0}" : "{8}",
                    i == 97 ? "{1}" : "{2}"
                ),
                "No",
                "bottle",
                "bottles",
                "of beer",
                "on the wall",
                "Take one down, pass it around",
                "Go to the store, buy some more",
                99 - i,
                (198 - i) % 100,
                Environment.NewLine
        ))));
    }
}

Note this is just a single statement :)

share|improve this answer

PHP - 252 bytes

$a=" bottles of beer";$b=str_replace("s","",$a);$c=" on the wall";for($i=98;$i;)echo($j=$i+1).$a.$c.", ".$j.$a.".
Take one down and pass it around, ".$i.($i-->1?$a:$b).$c.".

";echo"1".$b.$c.", 1".$b.".
Go to the store and buy some more, 99".$a.$c.".";

I hope I'll compress some more tomorrow.

share|improve this answer

Ruby 1.9.2p136 : 223

I'm no coward, you can read mine ;p

b="%d bottle%s of beer"
w=' on the wall'
99.downto(1){|z|s=b%[z,z>1?'s':'']
puts s+w+", "+s+".
"+(z>1?"Take one down and pass it around, "+b%[z-1,z>2?'s':'']+w+".

" :'Go to the store and buy some more, '+b%[99,'s']+w+".")}
share|improve this answer

C# (299 characters)

using System;class D{static void Main(){string a="s",z="",w=" on the wall",q=", ",p=".\n",b=" bottle",c=" of beer";for(int O=99;O>=1;)Console.WriteLine(O+b+(O>1?a:z)+c+w+q+O+b+(O>1?a:z)+c+p+(--O>0?"Take one down and pass it around, "+O:"Go to the store and buy some more, 99")+b+(O==1?z:a)+c+w+p);}}
share|improve this answer
1  
Your final line displays "99 bottle" instead of "99 bottles", and you have your loop starting from 19 instead of 99 (though that's probably just an oversight). – Nellius Jan 28 '11 at 10:22
show 3 more comments

JavaScript (7 functions)

Not golfed. This is intended as a (mostly) functional implementation of the song.

function firstUpper(s) {
    return s.slice(0, 1).toUpperCase() + s.slice(1);
}

function bottles(x) {
    return (x || "no more") + " " + (x == 1 ? "bottle" : "bottles") + " of beer";
}

function wall(x) {
    return bottles(x) + " on the wall";
}

function line1(x) {
    return wall(x) + ", " + bottles(x) + ".";
}

function line2(x, max) {
     return (x ? "take one down and pass it around, " + wall(x - 1) : "go to the store and buy some more, " + wall(max)) + ".";
}

function verse(x, max) {
    return [line1(x), line2(x, max)].map(firstUpper).join("\n") + "\n\n";
}


function song(max) {
    var text = "";
    for(var x = max; x >= 0; x--) {
        text += verse(x, max);
    }
    return text;
}

print(song(99));
share|improve this answer

PHP, 209 characters

<? $a=" bottle";$b=" of beer";$c=" on the wall";for($i=100;$i>1;)echo--$i>1?$i.$a."s$b$c, $i$a"."s$b.\nTake one down and pass it around, ":"$i$a$b$c, $i$a$b.\nGo to the store and buy some more, 99$a"."s$b$c.";

Output is shown here: http://codepad.viper-7.com/wmknQl.php53_t

Instead of using the third section in a for loop, it decreases the number on the fly when it is determining what string it needs to print out.

share|improve this answer
show 1 more comment

D: 310 Characters

import std.stdio, std.string;

void main()
{
    alias writefln p;
    enum b = "%s bottle%s of beer", w = " on the wall";
    auto s = (int r){return format(b, r, r > 1 ? "s" : "");};

    for(int r = 99; r > 0;)
    {
        p("%s%s, %s.", s(r), w, s(r));

        if(--r)
            p("Take one down pass it around, %s%s.\n", s(r), w);
        else
            p("Go to the store and buy some more, %s.", s(99));
    }
}
share|improve this answer

Rebmu — 172 characters

M N 99 Bdz[rj[n{ bottle}egN 1{s}{}{ of beer}]]loN[prRJ[b W{ on the wall}C{, }b P{.^/}eg--N 1{Take one down and pass it around}[Nm{Go to the store and buy some more}]cBwP]]

Could probably shave a few characters off, this was just a first try. :)

Here's equivalent Rebol which has the shorthand boiled out. Without any non-necessary whitespace, it would be 223 chars...still pretty competitive especially considering the clarity:

m: n: 99

b: does [
    rejoin [n { bottle} either n > 1 [{s}][{}] { of beer}]
]

loop n [
    print rejoin [
        b w: { on the wall} c: {, } b p: {.^/}

        either -- n > 1 [
            {Take one down, and pass it around}
        ] [
            n: m
            {Go to the store and buy some more}
        ]

        c b w p
    ]
]

Commented source code available on GitHub

share|improve this answer

PHP (249 chars)

My first golf attempt. It's kinda messy but that was to "fix" my problem with singular/plural in the the third last line of the song.

<?
$l=" on the wall";
$m=" of beer";
$x=" bottles";
for($i=99;$i>=1;$i--){
    $o="$i$x$m$l, $i$x$m.\n";
    $x=($i<3)?" bottle":$x;$o.=($i==1)?"Go to the store and buy some more, 99 
    bottles$m$l.":"Take one down and pass it around, ".($i-1)."$x$m$l.\n\n";
    echo$o;
}

No spaces

<?$l=" on the wall";$m=" of beer";$x=" bottles";for($i=99;$i>=1;$i--){$o="$i$x$m$l, $i$x$m.\n";$x=($i<3)?" bottle":$x;$o.=($i==1)?"Go to the store and buy some more, 99 bottles$m$l.":"Take one down and pass it around, ".($i-1)."$x$m$l.\n\n";echo$o;}

I also want to optimise it more later.

share|improve this answer

PHP (191)

Short tags must be turned on for this to work.

<? eval(gzinflate("]Á\nÂ0De*´ÅkPþ€Ç^»¥Á6+MJñß\rUAzYØÇììŒ4‡†Cȃ;¢)S2&Ê¡'D=™êxÚH{¨k%íq—FQlŸtíi¯NBZidÌ¥)wÑ7Jׄ–£ƒv-îÚ{Ø\0=ñìÚu’6NìEõ\rðûŸ|°fI{f^\"ùÀ-Æf~ÀóHÉQ×ë.ÿ-J¡^o"));?>

For those who are curious, here's what the gzinflate() returns:

$b=' bottles of beer';$w=' on the wall';for($i=99;$i>0;$i--){echo $i>1?"$i$b$w,$b.\nTake one down and pass it around, $i$b$w.\n\n":"1 bottle of beer$w, 1 bottle of beer.\nGo to the store and buy some more, 99 bottles of beer on the wall.";}

Broken down (with a few tweaks), that's:

$b=' bottles of beer';
$w=' on the wall';
for($i=99;$i>0;$i--){
   if ($i>1) {
      echo "$i$b$w,$b.\nTake one down and pass it around, $i$b$w.\n\n";
   } else {
      echo "1 bottle of beer$w, 1 bottle of beer.\nGo to the store and buy some more, 99 bottles of beer on the wall.";
   }
}

Oddly enough, my original attempt involved using gzinflate() on the inside for the final iteration, but once you encode it again for the eval() it makes it larger than had it not been there.

share|improve this answer
show 2 more comments
1 2 3

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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