99 Bottles Of Beer

65

16

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.

Nick Berardi

Posted 15 years ago

Reputation: 768

Question was closed 10 years ago

3Is 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. – None – 15 years ago

bzip2 - 553 bytes. not very good – gnibbler – 15 years ago

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 – 15 years ago

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 – 15 years ago

1@Nick: So I'm not against "creativity-based" criteria per se, but there needs to be a way to have a (somewhat) objective method to measure it. – Chris Jester-Young – 15 years ago

30"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 – 15 years ago

@ChrisJester-Young So, this just got bumped... presumably [tag:popularity-contest] fits now? – Bob – 12 years ago

5Still a good question though – Chris Laplante – 15 years ago

1

BTW: 1 bottle of beer.. is not the final verse.

– Sylwester – 12 years ago

@TheDoctor Why is this not a [popularity-contest]? – Justin – 12 years ago

This question is from codegolf.com. We are still discussing whether to allow it. I have 199 bytes solution, but will not post for now )

– Nakilon – 15 years ago

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. <Now everyone join me!> 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. – Thomas Eding – 14 years ago

Answers

70

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.

rubber boots

Posted 15 years ago

Reputation: 1 014

1Nice presentation, but this don't match request!! – F. Hauri – 12 years ago

A 'rot1' cipher, not the best attempt at obfuscation I've seen. The use of \b to 'remove' unwanted characters is also a bit disappointing. – primo – 11 years ago

100

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.

Peter Olson

Posted 15 years ago

Reputation: 7 412

Petition: rename this language to braindrunk ? – Cyoce – 10 years ago

9You only have 9 bottles there. You need 90 more! – Joe Z. – 13 years ago

99

Funciton

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

Since this looks ugly in StackExchange due to the extra line spacing, consider running the following code in your browser’s JavaScript console to fix that: $('pre').css('line-height',1)

                                            ╓┬────╖
     ╔════╗  ┌───╖                          ╟┘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 ║
              ╚═════╝╚═════════════════════════════════════════════════╝

Timwi

Posted 15 years ago

Reputation: 12 158

1That language is amazing, great job! – ceased to turn counterclockwis – 14 years ago

1I saw this on Esolang.org and liked the look of it. – M L – 10 years ago

1plus one, this is awesome – gyurisc – 14 years ago

56

jQuery + FireBug Console

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

;)

powtac

Posted 15 years ago

Reputation: 893

Devilishly clever. – Maxpm – 14 years ago

Actually, this is wrong, since the OP does not have the full lyrics... – JNF – 10 years ago

How this works? – VarunAgw – 12 years ago

1@JiminP Unfortunately, that's not a stable selector given how the answer order can change over time (in fact, it no longer works). – Muhd – 12 years ago

2@Muhd Still works as long as the question isn't changed - the first code block is the one in the question. – Bob – 12 years ago

@Bob, I was replying to JiminP's comment – Muhd – 12 years ago

@Muhd Oh, sorry. Yea, that's not gonna work. – Bob – 12 years ago

@JiminP that could be an awesome answer to this question: http://codegolf.stackexchange.com/questions/21114/weirdest-way-to-produce-a-stack-overflow

– DLeh – 12 years ago

2What 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 – 14 years ago

2Also works on Chrome's javascript console. – Spoike – 14 years ago

24

HQ9+ (1 character)

9

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

tobyodavies

Posted 15 years ago

Reputation: 991

1@muntoo I'm not sure HQ9+B is turing complete.. The command B polls the keyboard input and evaluates that as brainfuck so it's HQ9+ with an optonal Brainfuck interpreter. i.e. the program "B" in HQ9+B will poll stdin until it gets ! (or EOF) and interpret that as Brainfuck.. – Sylwester – 12 years ago

13

Why don't you use HQ9 B? It's Turing complete.

– Mateen Ulhaq – 14 years ago

20

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

Rob White

Posted 15 years ago

Reputation: 309

That can be reduced quite substantially. – Nellius – 15 years ago

2@Nellius Did you even read what ilivewithian said before his code? – Daniel Standage – 15 years ago

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 – 15 years ago

@Nellius It wasn't meant as a serious contender, on no level is this good code. I'm sure it can be reduced, made more efficient and generally improved considerably. – Rob White – 15 years ago

11+1 For being another C-style sacrificial lamb in an ocean of Perl. – Glenn Nelson – 15 years ago

18

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

celtschk

Posted 15 years ago

Reputation: 4 650

1Probably the most efficient and fastest solutions of these. – Tom Pažourek – 11 years ago

1@tomp Efficient timewise, very inefficient in the executable file size :) – seequ – 11 years ago

14

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

Nellius

Posted 15 years ago

Reputation: 568

1I 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 – 15 years ago

And now I have studied for it, I'm down to under 300 ;) – jcolebrand – 15 years ago

12

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

Timwi

Posted 15 years ago

Reputation: 12 158

11

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]

Jonathan Sternberg

Posted 15 years ago

Reputation: 279

11

Windows PowerShell (198)

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

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.

Joey

Posted 15 years ago

Reputation: 12 260

You're missing "on the wall." in the final line of output and after every bottle is taken down. – Iszi – 12 years ago

filter b{"$_ bottle$('s'*!!--$_) of beer"}(99..1|%{($_|b)+($w=' on the wall')+", $($_|b).";"Take one down and pass it around, $(--$_|b)$w. "})[0..196];"Go to the store and buy some more, $(99|b) $w." fixes that. Totals 199 characters. (Add a line break after $w before ") – Iszi – 12 years ago

Thanks for the fix. There was a superfluous space in there too, so the count is 198 instead. – Joey – 12 years ago

Definitely short, and this set a bar to try and go under!!! Though from my point of view, the appearance of a "magic number" like 196 was in the class of things I hope to be able to avoid because it captures (99 * 2) - 2. For an answer where you can change the bottle count in one place :) see http://codegolf.stackexchange.com/questions/2/99-bottles-of-beer/413#413

– HostileFork says dont trust SE – 15 years ago

11

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

Daniel Standage

Posted 15 years ago

Reputation: 634

10

Curl 19 characters

(requires internet connection)

curl -L j.mp/eGv9K5

Alexandru

Posted 15 years ago

Reputation: 5 485

7I consider this stretching it too far. – marcog – 15 years ago

8I consider it a joke. Many solutions can be hidden behind a query to a web server. – Alexandru – 15 years ago

3I like this one nevertheless. – pimvdb – 14 years ago

1If objective was shortest code, I'd give you a point for cleverness. – Neil – 14 years ago

9

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

Daniel Standage

Posted 15 years ago

Reputation: 634

Why not /usr/bin/env perl? – nyuszika7h – 11 years ago

1@nyuszika7h Insightful critique! ;) – Daniel Standage – 11 years ago

8

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.

aaaaaaaaaaaa

Posted 15 years ago

Reputation: 4 365

It looks like your bottle/bottles optimization is costing you more characters than it saves. – Yahel – 15 years ago

I'm not sure what you mean, what exactly would you change? – aaaaaaaaaaaa – 15 years ago

This one stops one verse too early. Last verse should go "no more bottles of beer on the wall, no more bottles..." -- See: http://99-bottles-of-beer.net/lyrics.html

– Már Örlygsson – 11 years ago

BTW, I managed a full, correct version in 233 bytes:
for(o,e,n=100,t=" on the wall";n-->-1;)o=e+t+", "+e+".<br>"+(n>-1?"Take one down, pass it around, ":"Go to the store and buy some more, ")+(e=(0>n?99:n||"no more")+" bottle"+(1!=n?"s":"")+" of beer")+t+".<p>",99>n&&document.write(o)
– Már Örlygsson – 11 years ago

@MárÖrlygsson Welcome to the site. The lyrics for this challenge are defined in the opening post. – aaaaaaaaaaaa – 11 years ago

7

C

I must have missed this question, so here's a version I posted as an answer elsewhere. It's a C quine based version. Compile and run to get next line of song. Repeat until bored. If code says "Time to go..." then enter number of beers next time you run as a command line argument.

// Time to go to the shop and get some beer
//
//
//
//
// #####.#####.#####.#####.#####.#####.#####
// ##.#####.#####.#####.#####.#####.#####.##
// #####.#####.#####.#####.#####.#####.#####
// ##.#####.#####.#####.#####.#####.#####.##

char *z [] = {
"void l(char *s,int b){int i;printf(\"// \");for(i=0;i<b;++i)printf(s);",
"printf(\"\\n\");}\nint main(int argc, char *argv[]){\nint i,j,k,x=%d;",
"char*p;\nif(!x&&argc==2)x=atoi(argv[1]);\nif(!x){printf(\"// Time to ",
"go to the shop and get some beer\\n//\\n//\\n//\\n//\\n\");k=7;\n",
"}else{printf(\"// %%d bottles of beer on the wall, %%d bottles of beer",
".\\n\",x,x);printf(\"// Take one down and pass it round, \");\n",
"if(x>1)printf(\"%%d bottles of beer on the wall.\\n//\\n\",x-1);\n",
"else printf(\"no more bottles of beer on the wall.\\n//\\n\");\n",
"k=x>2?x:2;l(\"  ^   \",x);l(\" / \\\\  \",x);l(\"/   \\\\ \",x);",
"l(\"|   | \",x);l(\"|Duf| \",x);l(\"|   | \",x);l(\"----- \",x);}\n",
"for(i=0;i<4;++i){\nprintf(\"// %%s\", i&1 ? \"##.\" : \"\");\n",
"for(j=i&1;j<k;++j)\nprintf(\"%%s#####\",j!=(i&1)?\".\":\"\");\n",
"printf(\"%%s\\n\",i&1?\".##\":\"\");}\nprintf(\"\\nchar *z [] = {\\n\");\n",
"for(i=0;i<sizeof z/sizeof z[0];++i){\nprintf(\"\\\"\");\n",
"for(p=z[i];*p;++p)\nswitch (*p){\ncase '\\n':printf(\"\\\\n\");break;\n",
"case '\\\\':printf(\"%%c%%c\",92,92);break;\n",
"case '%%':printf(\"%%c\",37);break;\ncase '\"':printf(\"%%c%%c\",92,'\"');break;\n",
"default:printf(\"%%c\", *p);break;}\nprintf(\"\\\",\\n\");}\n",
"printf(\"};\\n\");\nfor(i=0;i<sizeof z/sizeof z[0];++i)\n",
"printf(z[i],x?x-1:0);}\n",
};
void l(char *s,int b){int i;printf("// ");for(i=0;i<b;++i)printf(s);printf("\n");}
int main(int argc, char *argv[]){
int i,j,k,x=0;char*p;
if(!x&&argc==2)x=atoi(argv[1]);
if(!x){printf("// Time to go to the shop and get some beer\n//\n//\n//\n//\n");k=7;
}else{printf("// %d bottles of beer on the wall, %d bottles of beer.\n",x,x);printf("// Take one down and pass it round, ");
if(x>1)printf("%d bottles of beer on the wall.\n//\n",x-1);
else printf("no more bottles of beer on the wall.\n//\n");
k=x>2?x:2;l("  ^   ",x);l(" / \\  ",x);l("/   \\ ",x);l("|   | ",x);l("|Duf| ",x);l("|   | ",x);l("----- ",x);}
for(i=0;i<4;++i){
printf("// %s", i&1 ? "##." : "");
for(j=i&1;j<k;++j)
printf("%s#####",j!=(i&1)?".":"");
printf("%s\n",i&1?".##":"");}
printf("\nchar *z [] = {\n");
for(i=0;i<sizeof z/sizeof z[0];++i){
printf("\"");
for(p=z[i];*p;++p)
switch (*p){
case '\n':printf("\\n");break;
case '\\':printf("%c%c",92,92);break;
case '%':printf("%c",37);break;
case '"':printf("%c%c",92,'"');break;
default:printf("%c", *p);break;}
printf("\",\n");}
printf("};\n");
for(i=0;i<sizeof z/sizeof z[0];++i)
printf(z[i],x?x-1:0);}

Skizz

Posted 15 years ago

Reputation: 2 225

@DreamWarrior in regards to your proposed edit, have you considered putting your code in pastebin so that you could post it as a comment? – nderscore – 11 years ago

6

Python - a lot

Amidoinitrite?

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

....

  Ok, this is stupid. First of all, what the brainfuck are the bottles doing on the wall? They're not spiders nor picture frames. And how are they sitting on the wall?

94 bottles of beer on the wall, 9.. oops, they fell down. 94 bottles of beer on the floor, 94 bottles of beer.

  Second.. who the HQ9+ wants to keep track? I think I lost count after drinking the 2nd one...

Take one ... um... up, and pass it around,  .....  er.. a lot of bottles of beer still on the floor.

  Fourthly, what's with this passing around scheme? They're not j..I mean letters, yeah, or boxes of chocolate. We all can just take one and drink it. It's healthier too.

A pile of bottles of beer on the floor, a pile of bottles of beer.
Everyone take one up and drink it, still a whole bunch of bottles of beer on the floor.

  Um.. seventhly, are we really that many in this assembly that we can finish 200 or however many bottles we had in the beginning? Without passing out?

Go to the store and buy some more

  Yeah and who's gonna pay for it? Definitely not me. And how are you going to bring 300 bottles back from the store?
  In your car? Buddy, you're so drunk, you can't even C anything. Go home dude, go home. Take a cab."""

Additional reference (helped me a lot with the code): http://www.youtube.com/watch?v=Y0Z0raWIHXk

aditsu quit because SE is EVIL

Posted 15 years ago

Reputation: 22 326

6

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

user11

Posted 15 years ago

Reputation:

8I'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. :) – Chris Laplante – 15 years ago

10Javascript 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. – None – 15 years ago

2document.writeln works. – Chris Laplante – 15 years ago

4... for browsers – None – 15 years ago

I tried this out and my browser opened up 100 dialog boxes for printing the page. – Peter Olson – 15 years ago

It doesn't work on browsers as I said before. – None – 15 years ago

1I just tried this out in my browser console while on this page...apparently Chrome interprets 'print' literally and took me to the print dialog page 99 times (technically since page 1 of this question has the lyrics, it worked for me)...so a shorter program to output the lyrics is just "print()" (as long as it is run in the console while inspecting this page). – Xantix – 12 years ago

5JavaScript 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 – 14 years ago

console.log works in both node and browsers – anonymous coward – 15 years ago

Node? I use Rhino, I never tested it – None – 15 years ago

6

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

Hoa Long Tam

Posted 15 years ago

Reputation: 1 902

5

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

marinus

Posted 15 years ago

Reputation: 30 224

this .decode.decode stuff seemed stupid to me the first time i saw it, but i'm now using for practical purposes (to plop python code into my .bashrc as functions in an unobtrusive way), so thanks. – ixtmixilix – 13 years ago

5I count that the uncompressed code has 300 chars. Why compress it then? – Johannes Kuhn – 12 years ago

5

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/5fQmcd

Yahel

Posted 15 years ago

Reputation: 150

5

Rebmu — 167 characters

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

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

Here's equivalent Rebol which has the shorthand boiled out. Still pretty competitive especially considering the clarity:

m: n: 99

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

loop n [
    print combine [
        b w: { on the wall} c: {, } b p: {.} newline

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

        c b w p newline
    ]
]

Commented source code available on GitHub

HostileFork says dont trust SE

Posted 15 years ago

Reputation: 2 292

4

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

jcolebrand

Posted 15 years ago

Reputation: 1 683

1Your 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 – 15 years ago

@Nellius ~ Corrected ~ and thanks to your competitive code I revisited mine and removed some single insert blocks and reduced some preexisting constants in my own code. Now down to under 300 smoothly. – jcolebrand – 15 years ago

You can get it down to 293 by dropping "using System;" and changing "Console.WriteLine" to "System.Console.WriteLine" – Tester101 – 14 years ago

@Tester101 ~ Good call. Hadn't considered that! – jcolebrand – 14 years ago

4

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

derekerdmann

Posted 15 years ago

Reputation: 141

4

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

PleaseStand

Posted 15 years ago

Reputation: 5 369

4

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

Keith Randall

Posted 15 years ago

Reputation: 19 865

4

Go (263)

package main
import "fmt"
func main(){b,i,e,r:=fmt.Println,99,"bottles","of beer on the wall"
for i>0{b(i,e,r+",",i,e,r[:7]+".")
if i--;i<2{e=e[:6]}
if i>0{b("Take one down and pass it around,",i,e,r+`.
`)}}
b("Go to the store and buy some more,",99,e+"s",r+".")}

Slitione

Posted 15 years ago

Reputation: 41

3

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+".")}

Mike Bethany

Posted 15 years ago

Reputation:

3

(Oracle) SQL

No character count, I didn't golf it. Just found this a fun way to do it.

WITH
   bottles AS (
      SELECT LEVEL - 1 AS bottle 
      FROM dual
      CONNECT BY LEVEL <= &number_of_bottles + 1
   ),
   fragments AS (
      SELECT
         'no more ' AS none,
         'bottles of beer' AS supply,
         ' on the wall' AS wall,
         'Take one down and pass it around' AS drink,
         'Go to the store and buy some more' AS refill,
         CHR(13) || CHR(10) AS newline
      FROM dual
   ),
   combined AS (
      SELECT
         b.bottle,
         DECODE(
            b.bottle, 
            1, b.bottle || ' ' || REPLACE(f.supply, 's'),
            0, f.none || f.supply,  
            b.bottle || ' ' || f.supply
         ) AS supply
      FROM bottles b
      CROSS JOIN fragments f

   ),
   two_lines AS (
      SELECT LEVEL AS line
      FROM dual
      CONNECT BY LEVEL <= 2
   )
SELECT
   CASE l.line
      WHEN 1 THEN REPLACE(c1.supply, 'n', 'N') || f.wall || ', ' || c1.supply || '.'
      WHEN 2 THEN DECODE(b.bottle, 0, f.refill, f.drink) || ', '  || c2.supply || f.wall || '.' 
   END AS song 
FROM bottles b
LEFT JOIN combined c1 ON (c1.bottle = b.bottle)
LEFT JOIN combined c2 ON (c2.bottle = DECODE(b.bottle - 1, -1, &number_of_bottles, b.bottle - 1))
CROSS JOIN two_lines l
CROSS JOIN fragments f
ORDER BY
   b.bottle DESC,
   l.line;

SQB

Posted 15 years ago

Reputation: 681

3

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.

Aurel Bílý

Posted 15 years ago

Reputation: 1 083

2

Is this cheating? In Python, maybe not beautiful, but short & sweet.

import urllib2
response = urllib2.urlopen('http://pastebin.com/raw.php?i=HCCqYj2z')
html = response.read()
print(html

DudeGuy

Posted 15 years ago

Reputation: 21

I think it is :-) – John Dvorak – 12 years ago

People have to learn to forbid network access. – Johannes Kuhn – 12 years ago

2

Lilypond - 6435

I can't resist reposting my entry from 99-bottles-of-beer.net. Here is the first part of the output. You can find the rest here.

First eight bars of the song in music notation

Note: The code is obviously not golfed. Moreover, it follows the "official" 99-bottles-of-beer.net lyrics, with the "No more bottles" last verse. Adjusting this if desired is an exercise for the reader.

% Lilypond is a music engraving system with an
% embedded Scheme interpreter.
% http://lilypond.org

\include "english.ly"

% Necessary because we use deep recursion
#(debug-set! stack 0)

\header{
  title =        "Ninety-Nine Bottles of Beer"
  composer =     "Traditional"
  arranger =     \markup{ "Nate Eldredge" }
}

\version "2.8.7"

totalbottles = #99

startmelody = {
  \time 6/8
  \clef treble
  \key c \major
  \autoBeamOff
}

endmelody = {
  \bar "|."
}

% text = \lyricmode {
%   Nine -- ty nine bot -- tles of beer on the wall
%   Nine -- ty nine bot -- tles of beer __
%   Take one down and pass it a -- round
%   Nine -- ty eight bot -- tles of beer on the wall
% }

zerosyl = { }
onesyl = \relative c''{ c4. }
twosyl = \relative c''{ c4 c8 }
threesyl = \relative c''{ c8 c8 c8 }
foursyl = \relative c''{ c16 c16 c8 c8 }
fivesyl = \relative c''{ c16 c16 c8 c16 c16 }

#(define (count-syllables L)
  (if (null? (ly:music-property L 'text))
   (apply + (map count-syllables (ly:music-property L 'elements)))
   1))

% FIXME - check the syllabication
zero = \lyricmode { } % because "seventy" will become { \seventy \zero }
one = \lyricmode { one }
two = \lyricmode { two }
three = \lyricmode { three }
four = \lyricmode { four }
five = \lyricmode { five }
six = \lyricmode { six }
seven = \lyricmode { se -- ven }
eight = \lyricmode { eight }
nine = \lyricmode { nine }
ten = \lyricmode { ten }
eleven = \lyricmode { e -- le -- ven }
twelve = \lyricmode { twelve }
thirteen = \lyricmode { thir -- teen }
fourteen = \lyricmode { four -- teen }
fifteen = \lyricmode { fif -- teen }
sixteen = \lyricmode { six -- teen }
seventeen = \lyricmode { se -- ven -- teen }
eighteen = \lyricmode { eigh -- teen }
nineteen = \lyricmode { nine -- teen }
twenty = \lyricmode { twen -- ty }
thirty = \lyricmode { thir -- ty }
forty = \lyricmode { for -- ty }
fifty = \lyricmode { fif -- ty }
sixty = \lyricmode { six -- ty }
seventy = \lyricmode { se -- ven -- ty }
eighty = \lyricmode { eigh -- ty }
ninety = \lyricmode { nine -- ty }
nomore = \lyricmode { no more }
error = \lyricmode { oh shit }

#(define (speak-small n)
  (cond 
   ((= n 0) zero)
   ((= n 1) one)
   ((= n 2) two)
   ((= n 3) three)
   ((= n 4) four)
   ((= n 5) five)
   ((= n 6) six)
   ((= n 7) seven)
   ((= n 8) eight)
   ((= n 9) nine)
   ((= n 10) ten)
   ((= n 11) eleven)
   ((= n 12) twelve)
   ((= n 13) thirteen)
   ((= n 14) fourteen)
   ((= n 15) fifteen)
   ((= n 16) sixteen)
   ((= n 17) seventeen)
   ((= n 18) eighteen)
   ((= n 19) nineteen)
   (else error)))

#(define (speak-tens n)
  (cond
   ((= n 1) ten)
   ((= n 2) twenty)
   ((= n 3) thirty)
   ((= n 4) forty)
   ((= n 5) fifty)
   ((= n 6) sixty)
   ((= n 7) seventy)
   ((= n 8) eighty)
   ((= n 9) ninety)
   (else error)))

#(define (speak-number n)
  (cond
   ((= n 0) nomore)
   ((< n 20) (speak-small n))
   (else (make-sequential-music 
      (list
       (speak-tens (quotient n 10))
       (speak-small (modulo n 10)))))))

#(define (sing-syllables k)
  (cond
   ((= k 0) zerosyl)
   ((= k 1) onesyl)
   ((= k 2) twosyl)
   ((= k 3) threesyl)
   ((= k 4) foursyl)
   ((= k 5) fivesyl)))

#(define (sing-number n) (sing-syllables (count-syllables (speak-number n))))

SingNumber = #(define-music-function (parser location n)
           (integer?)
           (ly:music-deep-copy (sing-number n)))
SpeakNumber = #(define-music-function (parser location n)
           (integer?)
        (ly:music-deep-copy (speak-number n)) )

#(define (capitalize! s) (string-set! s 0 (char-upcase (string-ref s 0))))
#(define (capitalize s)
  (let ((l (string->list s)))
   (list->string (cons (char-upcase (car l)) (cdr l)))))

% takes a list of music objects
#(define (capitalize-lyric-list L)
  (cond 
   ((null? L))
   ((not (null? (ly:music-property (car L) 'text))) 
    (ly:music-set-property! (car L) 'text 
     (capitalize (ly:music-property (car L) 'text))))
   (else (capitalize-lyric-list
      (append 
       (ly:music-property (car L) 'elements)
       (cdr L))))))

CapitalizeLyric = 
       #(define-music-function (parser location lyr)
     (ly:music?)
     (let ((newlyr (ly:music-deep-copy lyr)))
      (capitalize-lyric-list (list newlyr))
      newlyr))

melodyone =   \relative c''{ g8 g g | c c c c4 r8 | }
melodytwo = \relative c''{ a8 a a | d4.~ d8 r8 r8 | b4 b8 b4 b8 | b8 b b b4 r8 | }
melodytwofinal = \relative c''{ a8 a a | d4.~ d8 r4 | b8 b8 b8 b4 b8 | b4 b8 b4 r8 | }
melodythree = \relative c''{ a8 a b | c c c c4 r8 |}

lyricsone = \lyricmode{ of beer on the wall, }
lyricstwo = \lyricmode{ of beer.  Take one down and pass it a -- round, }
lyricstwofinal = \lyricmode{ of beer.  Go to the store and buy some more, }
lyricsthree = \lyricmode { of beer on the wall. }

bottle = \lyricmode{ bot -- tle }
bottles = \lyricmode{ bot -- tles }

PluralBottle = #(define-music-function (parser location n)
           (integer?)
         (if (= n 1) bottle bottles))


SingVerse = #(define-music-function (parser location n)
          (integer?)
          (let 
           ((nn (if (> n 0) (- n 1) totalbottles))
        (meltwo (if (> n 0) melodytwo melodytwofinal)))
           #{
          { { \SingNumber #$n }}
          \melodyone
           { \transpose c d { \SingNumber #$n }}
          $meltwo
           {  \transpose c' g { \SingNumber #$nn }}
          \melodythree
          #}))

SpeakVerse = #(define-music-function (parser location n)
          (integer?)
          (let 
           ((nn (if (> n 0) (- n 1) totalbottles))
        (lyrtwo (if (> n 0) lyricstwo lyricstwofinal)))
          #{
           \CapitalizeLyric \SpeakNumber #$n
           \PluralBottle #$n
           \lyricsone
           \SpeakNumber #$n
           \PluralBottle #$n
           $lyrtwo
           \SpeakNumber #$nn
           \PluralBottle #$nn
           \lyricsthree
           #}))

SingVerses = #(define-music-function (parser location nstart nend)
          (integer? integer?)
           (if (>= nstart nend)
        (let ((nextverse (- nstart 1)))
         #{ \SingVerse #$nstart \SingVerses #$nextverse #$nend #})
        #{ #} ))

SpeakVerses = #(define-music-function (parser location nstart nend)
          (integer? integer?)
           (if (>= nstart nend)
        (let ((nextverse (- nstart 1)))
         #{ \SpeakVerse #$nstart \SpeakVerses #$nextverse #$nend #})
        #{ #} ))


\score{
  {
    <<
      \new Voice = "one" {
    \transpose c' g  {
      \startmelody
      \SingVerses #totalbottles #0
      \endmelody 
    }
      }
      \new Lyrics \lyricsto "one" { 
    \SpeakVerses #totalbottles #0
      }
    >>
  }
  \layout { }
  \midi { }
}

Nate Eldredge

Posted 15 years ago

Reputation: 2 544

2

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.

Mr. Llama

Posted 15 years ago

Reputation: 2 387

I think you're supposed to make this a community wiki post, like all the other answers. – Peter Olson – 15 years ago

There we go! Fixed it. Thanks for pointing that out. Still new to this stack exchange. – Mr. Llama – 15 years ago

2

Some pre-processor and C++ template metaprogramming.

#include <stdio.h>
#define x "%d bottle%s of beer on the wall"
#define y ", %d bottle%s of beer."
#define z "\nTake one down and pass it around, "
#define T template
T<int V>struct B{B(){printf(x y z x".\n\n" ,V,"s",V,"s",V-1,V-1==1?"":"s");B<V-1>();}};
T<>struct B<1>{B(){printf(x y "\nGo to the store and buy some more, "x".\n\n",1,"",1,"",99,"s");}};
void main(){B<99>();}

dwayne963

Posted 15 years ago

Reputation: 21

2

F# - 214 209 characters

for i=99 downto 1 do stdout.Write("{0}{1}{2}, {0}{1}.\n{3}{1}{2}.\n",i," bottles of beer"," on the wall",if i>1 then"Take one down and pass it around, "+string(i-1)else"Go to the store and buy some more, 99")

nharren

Posted 15 years ago

Reputation: 383

2

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

Jonathan M Davis

Posted 15 years ago

Reputation: 705

2

PHP 244 226 char

I've been working with PHP for a while, but this is my first crack at code golf. Here's what I came up with

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

Golfed it some more!

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

Brobin

Posted 15 years ago

Reputation: 201

Welcome to Programming Puzzles and Code Golf! – trichoplax – 11 years ago

I don\t know PHP too well, but would for($i=99;$i-->0;) work? Also, remove the unnecessary whitespace in assignments, $b=' bottles of beer'; – seequ – 11 years ago

2

Dart

class Bottle{
  int _amount;
  String _kind,_place;
  get amount() => _amount;
  set amount(int amt){
    if(amt<0){
      _amount = 99;
      throw "Go to store and buy some more, ${toStr(true)}.";
    }
    if(amt>99) throw "I'm drunk.";
    _amount = amt;
  }
  get place() => _place;
  set place(String plc){
    _place = plc;
  }
  get kind() => _kind;
  set kind(String knd){
    _kind = knd;
  }
  Bottle(amt,knd,plc){
    amount = amt;
    kind = knd;
    place = plc;
  }
  String toStr(bool long){
    String plural = amount==1?'':'s';
    String append = long?" on $place":'';
    if(amount>0) return "$amount bottle$plural of $kind$append";
    else return "No bottles of $kind$append";
  }
}
main(){
  Bottle beer = new Bottle(99,'beer','the wall');
  print("${beer.toStr(true)}, ${beer.toStr(false)}.");
  while(beer.amount-->0){
    print("Take one down and pass it around, ${beer.toStr(true)}.");
    print("${beer.toStr(true)}, ${beer.toStr(false)}.");
  }
}

JiminP

Posted 15 years ago

Reputation: 3 264

1+1 for if(amt>99) throw "I'm drunk.";. – awe – 14 years ago

2

99

"99" is a language I invented specifically for 99-bottles-of-beer.net

I'm unable to present my program here, since the markdown format doesn't appear to let me show an empty source file. But you probably already have a copy of the program on your system; look for /dev/null or NUL:.

Here's the entry on 99-bottles-of-beer.net, and here's the Github page.

Keith Thompson

Posted 15 years ago

Reputation: 289

2

oOo CODE: 6436 Characters

Self documenting code on its finest. It's based on the brainfuck answer. Din't have time for fancy ascii art so here it is:

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.
94 bottlEs oF bEEr oN tHe waLl, 94 bottleS of bEeR, taKE oNE dOWn aNd pAsS it arouNd, 93 bottleS of bEeR on tHe wAlL.
93 bottlES oF beEr on thE waLL, 93 bottlEs oF bEEr, takE onE doWN aND pASs it arOuND, 92 bottlEs oF bEEr oN tHE wALl.
92 bottleS of bEeR on tHe wAlL, 92 bottlES oF beER, taKe oNe dOwN anD paSS iT aroUnD, 91 bottlES oF beER oN thE waLL.
91 bottlEs oF bEEr on thE wALl, 91 bottleS of bEeR, taKE oNE dOWn aNd pAsS it arouNd, 90 bottleS of bEeR on tHe wAlL.
89 bottlES oF beER oN the waLL, 89 bottlEs oF bEEr, takE onE doWN aND pASs iT aROuNd, 88 bottlEs oF bEEr oN tHE wALl.
88 bottleS of bEeR on tHe wAlL, 88 bottlES oF beER, taKe oNe dOwN anD paSS iT arOUnD, 87 bottlEs of beER oN thE waLL.
87 bottlEs oF bEEr oN tHE wALl, 87 bottleS of bEeR, taKE oNE dOWn aNd pAsS it aRoUNd, 86 bottleS of bEeR on tHe wAlL.
86 bottlES oF beER oN thE waLL, 86 bottlEs oF bEEr, takE onE doWn aNd pAss it aRouNd, 85 bottles of bEer on tHe wAll.
85 bottles oF beer on the wAlL, 85 bottleS oF beER, taKe one dOwN anD paSS iT arOund, 84 bottlES oF beER oN thE wall.
84 bottles oF bEEr oN tHe waLl, 84 bottleS of beer, taKE oNE dOWn aNd pAsS it aRoUNd, 83 bottleS of bEeR on the wall.
83 bottlEs of beER oN thE walL, 83 bottlEs oF bEer, takE onE doWN aND pAss iT aROuND, 82 bottlEs oF bEEr on tHe wAll.
82 bottleS of beeR on the walL, 82 bottlEs oF beEr, take one dowN anD paSs iT arOunD, 81 bottles of beEr oN thE wAll.
81 bottles of beer on thE wall, 81 bottles of beer, take one down and pass it around, 80 bottlEs of beer on the wALl.
79 bottlEs oF beEr oN thE waLL, 79 bottles of bEer, takE oNe down and pass it around, 78 bottles of beER on tHe wAll.
78 bottleS of beeR on the walL, 78 bottlEs oF beEr, take one dOWn and pass it around, 77 bottles of beer on the wall.
77 bottlES of bEer on tHe wAll, 77 bottlEs of beeR, taKe oNe dOwn and pasS iT around, 76 bottles of bEEr on the wALl.
76 bottles of beer on the wall, 76 bottles oF beer, takE onE doWn aNd pAss it aRouNd, 75 bottles of bEer on tHe wALL.
75 bottles of beer on the wall, 75 bottles of beer, take one dOWn anD pAss iT arOunD, 74 bottlEs oF beEr oN thE waLl.
74 bottles oF beer on the wall, 74 bottles of beer, take one down and pass it around, 73 bottlEs of beeR on the walL.
73 bottlEs oF beER on thE waLL, 73 bottles of bEer, takE onE doWN and pass it around, 72 bottles of beer on the wall.
72 bottles of beer on the wall, 72 bottles oF beEr, take one dowN anD paSs iT arOunD, 71 bottlEs oF beEr oN tHe wall.
71 bottles of beer on the waLL, 71 bottleS of beeR, taKe oNe dOwn and pasS it aroUND, 70 bottlEs of beeR on the walL.
69 bottleS of beer on the walL, 69 bottles of beer, take oNe down and pass it around, 68 bottles oF beer on the wall.
68 bottlEs of beeR on the walL, 68 bottles oF beEr, take one dOWn and pass it around, 67 bottles of beer on tHe waLl.
67 bottles of bEer on tHe wAll, 67 bottleS of beeR, taKe oNe dOwn aND pass it around, 66 bottles of beer on the wall.
66 bottles of bEer oN thE waLl, 66 bottles oF beer, takE onE doWn aNd pAss it aROUnd, 65 bottles of beer oN the wall.
65 bottlEs of beer on the wall, 65 bottles of beeR, take one dowN anD paSs iT arOunD, 64 bottlEs oF beEr oN thE waLL.
64 bottlES of beer on the wall, 64 bottles of beer, take one down and pass it around, 63 bottleS of beeR on the walL.
63 bottlEs oF beEr oN thE waLl, 63 bottles of beer, take one down anD pass it aRouNd, 62 bottles of bEer on tHe wAll.
62 bottlEs of beer on the wall, 62 bottles of beer, take one down and pAss iT aRounD, 61 bottlEs oF beEr oN tHe waLl.
61 bottles of bEer on tHE wall, 61 bottles of beer, takE one down and pass it around, 60 bottlEs of beer on the wall.
59 bottles oF beEr oN thE waLl, 59 bottlES of bEer, takE onE doWn aNd pAss it aRouNd, 58 bottles oF beer on the wall.
58 bottles of beer on the wall, 58 bottles of bEer, take one dowN anD paSs iT aRounD, 57 bottlEs oF beEr oN tHe wall.
57 bottles of beer on the wall, 57 bottles of beer, take onE down and pasS it aroUnd, 56 bottleS of beeR on tHE wall.
56 bottles of beer on the wall, 56 bottles of beer, taKe oNe doWn aNd pAss it aRouNd, 55 bottles of bEer on tHe wAll.
55 bottleS of bEEr on the wall, 55 bottles of beer, take one dOWn and pass it around, 54 bottles of bEer oN thE waLl.
54 bottles of bEer on tHe wAll, 54 bottleS of beeR, taKe oNe dOWN and pass it arouND, 53 bottles of beer on the wall.
53 bottles of beer on tHe waLl, 53 bottles of beer, take one dOwn aNd pAss it aRouNd, 52 bottles of bEer on tHe wAll.
52 bottlEs of beeR on the walL, 52 bottlES of beEr, take one dowN aNd pasS it aRound, 51 bottles of bEer on the wall.
51 bottlES of beer on the wall, 51 bottles of beer, take one down and pASs iT aroUnd, 50 bottleS of beeR oN the walL.
49 bottlEs oF bEer on the wall, 49 bottles of beer, take one dOwn aNd pAss it aRouNd, 48 bottles of bEer on tHe wAll.
48 bottleS of beeR oN the wall, 48 bottles of beer, take one down and pass it aroUNd, 47 bottlEs oF beEr oN thE wAll.
47 bottles of bEer on tHe wAll, 47 bottles of beer, take onE down and pASs iT around, 46 bottles of beer on the wall.
46 bottlEs oF beEr oN thE waLl, 46 bottles of bEer, takE onE doWn aNd pASS it around, 45 bottles of beer on the wall.
45 bottles of beer oN the wALl, 45 bottlEs oF beEr, take one dowN anD paSs iT arOunD, 44 bottles of beer on the wall.
44 bottles of beer on the wall, 44 bottles of beer, take oNe dOwn and pasS it aroUnd, 43 bottlEs of beeR oN the walL.
43 bottlEs oF beEr oN tHe wall, 43 bottles of beer, take one down and pass it around, 42 bottles of beer on thE wall.
42 bottleS of beeR on the walL, 42 bottlEs oF beEr, take one dowN aNd pass it around, 41 bottles of beeR on tHe waLl.
41 bottles of bEer on tHe wAll, 41 bottlEs of beeR, take oNe dOWn anD pAsS it aRoUNd, 40 bottleS of bEeR on the walL.
39 bottlES oF beER oN thE waLL, 39 bottles oF beer, take one dOW

Def

Posted 15 years ago

Reputation: 602

2

CJam, 184 characters

100,{[:A" bottles of beer":B" on the wall":C", "AB".
Take one down and pass it around, "A(BC".

"]+}%W%-2<)-3" bottle of beer":Dt1DC", "1D".
Go to the store and buy some more, "99BC"."

Try it online here

Optimizer

Posted 15 years ago

Reputation: 25 836

Not sure if CJam is allowed here. The question was asked on 2011-01-27, while CJam's initial release was published on SourceForge on 2014-04-05. (I upvote it anyway for founding a language not used in the previous 113 answers.) – manatwork – 11 years ago

1Not contending for an accepted answer :) and yes, the answer is invalid. – Optimizer – 11 years ago

2

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.

Neddy

Posted 15 years ago

Reputation: 181

2

ArnoldC

IT'S SHOWTIME
HEY CHRISTMAS TREE b
YOU SET US UP 99
HEY CHRISTMAS TREE a
YOU SET US UP 1
STICK AROUND a
TALK TO THE HAND b
TALK TO THE HAND "bottles of beer on the wall,"
TALK TO THE HAND b
TALK TO THE HAND "bottles of beer. Take one down, pass it around,"
GET TO THE CHOPPER b
HERE IS MY INVITATION b
GET DOWN 1
ENOUGH TALK
TALK TO THE HAND b
TALK TO THE HAND "bottles of beer on the wall."
GET TO THE CHOPPER a
HERE IS MY INVITATION b
LET OFF SOME STEAM BENNET 2
ENOUGH TALK
CHILL
TALK TO THE HAND "1 bottle of beer on the wall, 1 bottle of beer. Take one down and pass it around, no more bottles of beer on the wall."
TALK TO THE HAND "No more bottles of beer on the wall, no more bottles of beer. Go to the store and buy some more, 99 bottles of beer on the wall."
YOU HAVE BEEN TERMINATED

"Milk is for babies. When you grow up you have to drink beer." -Arnold Schwarzenegger

Mama Fun Roll

Posted 15 years ago

Reputation: 7 234

1

C

#include <stdio.h>
#include <stdlib.h>

void printBottles(int i, char * pP)
{
    printf("%d bottl%s of beer on the wall, %d bottl%s of beer.\n",i,pP,i,pP);
}
void printTakeBottleDown(int i)
{
    printf("Take one down and pass it around, %d bottles of beer on the wall.\n\n",i);
}

int main()
{
    int i = 99;

    while(i>1)
    {
        printBottles(i--,"es");
        printTakeBottleDown(i);
    }

    printBottles(1,"e");
    printf("Go to the store and by some more, 99 bottles of beer on the wall.");

    return 0;
}

Pemdas

Posted 15 years ago

Reputation: 141

1

Python 3.1(268):

b=99
a=" bottles of beer"
w=" on the wall"

while 1:
 for i in range(0,99):
  print(`b`+a+w+", "+`b`+a+".")
  if b>0:
   print(" Take one down and pass it around, "+`(b-1)`+a+w+".")
   b-=1
  else:
   b=99
   print(" go to the store and buy some more, "+`(b)`+a+w+".")

John

Posted 15 years ago

Reputation: 251

What's the problem? – John – 15 years ago

I wasn't the downvoter, however, your program's output does not conform to the spec. Read what happens after 1---it loops back to 99, but with different text. – Chris Jester-Young – 15 years ago

@Chris: Could you give me your output please? On my machine, it stops at 0 bottles of beer on the wall like it's supposed to. – John – 15 years ago

It's not supposed to stop at 0. It's supposed to loop back to 99 with text "Go to the store and buy some more", and run forever. Read the question again. – Chris Jester-Young – 15 years ago

@Chris: IMHO, it was not very clear that it was supposed to loop forever(he never says that), but I fixed it now. – John – 15 years ago

1

JavaScript (291 characters):

function w(b){document.writeln(b+"<br/>")}function s(b){return b+" bottle"+(b==1?"":"s")}for(var c=99,o=" of beer",a="around",l=" on the wall",p=".";c>0;){w(s(c)+o+l+", "+s(c)+o+".");--c>0?w("Take one down, pass it "+a+", "+s(c)+o+l+p):w("Go to the store, and buy some more, "+s(99)+o+l+p)};

Chris Laplante

Posted 15 years ago

Reputation: 652

1

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.

Kevin Brown

Posted 15 years ago

Reputation: 5 756

1That's... not the output expected (from the original post) although maybe an alternate variation of "99 Bottles". – Mr. Llama – 15 years ago

1

JAVA (353)

public static void main(String[] args) {
    String s[] = new String[]{"s", "", "Take one down and pass it around, %d bottle%s of beer on the wall.\n", "Go to the store and buy some more, 99 bottles of beer on the wall\n"};
    for (int i=1; i<100;) System.out.println(String.format("%d bottle%s of beer on the wall, %d bottle%s of beer.\n%s", 100-i, s[i/99], 100-i, s[i++/99], String.format(s[i/100+2], 100-i, s[i/99])));
}

rodrigopc

Posted 15 years ago

Reputation: 11

1

Java (543 Characters)

Here is my attempt at this challenge.

public class BottlesOfBear {

    public static void main(String[] args) {

        final int BOTTLEAMOUNT = 99;
        int bottleCount = 99;

        for (int i = 0; i < BOTTLEAMOUNT; i++) {
            System.out.println(bottleCount + (bottleCount == 1 ? " bottle " : " bottles ") + "of beer on the wall, " + bottleCount + (bottleCount == 1 ? " bottle " : " bottles ") + "of beer.");
            bottleCount--;
            System.out.println("Take one down and pass it around, " + bottleCount + (bottleCount == 1 ? " bottle " : " bottles ") + "of beer on the wall.");
        }

    }

}

Martin Wheeler

Posted 15 years ago

Reputation: 11

1

PHP (225 chars)

<?=preg_replace('/\w/e','$0=="b"?"$n bottle".($n>1?"s":"")." of beer":($0=="w"?"on the wall":(--$n?"Take one down and pass it around":(($n=99)?"Go to the store and buy some more":"")))',str_repeat('b w, b.
t, b w.

',$n=99));

user2566503

Posted 15 years ago

Reputation: 11

1

Python 2 (1129 1120 chars)

import zlib,base64
print zlib.decompress(base64.b64decode(b"eF6dmk1u2mAABfec4jtAhJr/cIJeoBcA4apVCa6AKOrtiyJ1ldeZJ2/t8ZvdCOxvsxm7+XI5TOcxfx+7aTqN+TguP6bxvj0cbsbm0/316tv213SlprGf349je9yP39vzefy8jO1pfjvur0+90Op6tWIgDVTaZ9MikAYq7ZNpEUgDlfbRtAikgUr7YFoE0kClvTctAmmg0t6ZFoE0UGlvTYtAGqi0X0yLQBpotC8YoauWgTRQaa1SDKSBSmuVYiANVFqrFANpoNJapRhIA5XWKsVAGqi0VikG0kCltUoxkAYqrVWKgTRQaa1SDKSBRvtslWIgDVRaqxQDaaDSWqUYSAOV1irFQBqotFYpBtJApbVKMZAGKq1VioE0UGmtUgykgUprlWIgDVRaqxQDaaDRPlmlGEgDldYqxUAaqLRWKQbSQKW1SjGQBiqtVYqBNFBprVIMpIFKa5ViIA1UWqsUA2mg0lqlGEgDldYqxUAaaLSPVikG0kCltUoxkAYqrVWKgTRQaa1SDKSBSmuVYiANVFqrFANpoNJapRhIA5XWKsVAGqi0VikG0kCltUoxkAYa7YNVioE0UGmtUgykgUprlWIgDVRaqxQDaaDSWqUYSAOV1irFQBqotFYpBtJApbVKMZAGKq1VioE0UGmtUgykgUZ7b5ViIA1UWqsUA2mg0lqlGEgDldYqxUAaqLRWKQbSQKW1SjGQBiqtVYqBNFBprVIMpIFKa5ViIA1UWqsUA2mg0d5ZpRhIA5XWKsVAGqi0VikG0kCltUoxkAYqrVWKgTRQaa1SDKSBSmuVYiANVFqrFANpoNJapRhIA5XWKsVAGmi0t1YpBtJApbVKMZAGKq1VioE0UGmtUgykgUprlWIgDVRaqxQDaaDSWqUYSAOV1irFQBqotFYpBtJApbVKMZAGGq1Fys50LnFaoeyo1BKn5clOICxxWpvsw94Sp4XJ3pcvcVqV7DXUEqclyf7dLXFaj+xH0xLnv5b8Lwpw+/PD69XXeVzmD+J8mU/Th3L39mec59dpvF6v3Azr0F83Y1CM")).decode()

cemper93

Posted 15 years ago

Reputation: 670

1

Mathematica 7, 281

b[i_]:=If[i==1,ToString@i<>" bottle",ToString@i<>" bottles"]
w=" of beer on the wall";
s[i_]:=If[i==0,".
   Go to the store and buy some more, "<>b@99<>w<>".",
  ".
   Take one down and pass it around, "<>b@i<>w<>"."]
j:=100-i
Do[Print[b@j<>w<>", "<>b@j<>StringDrop[w,-12]<> 
   s@(j-1)],{i,99}]

user1430

Posted 15 years ago

Reputation:

1

PHP, 229 223 chars

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

Not very glamorous though.

Samuli K

Posted 15 years ago

Reputation: 51

1

C++, 266 chars

int b=99;string m=" bottles of beer on the wall, ";string n=" bottles of beer, take one down and pass it around, ";string r=" bottles of beer.\n";void p(int b){cout<<b<<m<<b<<n<<--b<<r;}while(b!=0){p(b);b--;if(b<1){cout<<"\ngo to the store and buy some more.";b=99;}  

This assumes that <iostream> is #included

Nate Koppenhaver

Posted 15 years ago

Reputation: 380

1

PYTHON 221 CHARS

a="%d bottles of beer on the wall"
b="Take one down and pass it around, "
c="Go to the store and buy some more, %s."%a
d=', '+ a[0:18]+'.\n'
for i in range(99,1,-1):print(a+d+b+a)%(i,i,i-1)+'.\n'
print(a+d+c%99)%(i-1,i-1)

killown

Posted 15 years ago

Reputation: 109

1

Python 2.x - (306 293 288 bytes)

So, this is was an older script of mine. It is a one-liner and heavily golfed. Demo

print(lambda x:x(x,99,lambda c,w=1,p=0:"%s %s of beer%s"%(c or"nN"[p]+"o more","bottle"+"s"*(c!=1)," on the wall"*w)))(lambda x,c,y:c+1and"%s, %s.\n%s"%(y(c,1,1),y(c,0),"Take one down and pass it around, %s.\n\n"%y(c-1)*(c>0))+x(x,c-1,y)or"Go to the store and buy some more, %s.\n"%y(99))

293 bytes version

print(lambda x:x(x,99,lambda c,w=1,p=0:"%s %s of beer%s"%(c or("n","N")[p]+"o more","bottle"+"s"*(c!=1)," on the wall"*w)))(lambda x,c,y:c+1and"%s, %s.\n%s"%(y(c,1,1),y(c,0),"Take one down and pass it around, %s.\n\n"%y(c-1)*(c>0))+x(x,c-1,y)or"Go to the store and buy some more, %s.\n"%y(99))

306 bytes version

print(lambda x:x(x,99,lambda c,w=1,p=0:"%s %s of beer%s"%(c or("n","N")[p]+"o more","bottle"+("s","")[c==1],(""," on the wall")[w])))(lambda x,c,y:c+1and"%s, %s.\n%s"%(y(c,1,1),y(c,0),c and"Take one down and pass it around, %s.\n\n"%y(c-1)or"")+x(x,c-1,y)or"Go to the store and buy some more, %s.\n"%y(99))

Fixing it for Python 3 would add two characters (untested):

print((lambda x:x(x,99,lambda c,w=1,p=0:"%s %s of beer%s"%(c or"nN"[p]+"o more","bottle"+"s"*(c!=1)," on the wall"*w)))(lambda x,c,y:c+1and"%s, %s.\n%s"%(y(c,1,1),y(c,0),"Take one down and pass it around, %s.\n\n"%y(c-1)*(c>0))+x(x,c-1,y)or"Go to the store and buy some more, %s.\n"%y(99)))

I would like to note that it isn't exactly elegant. To change the starting amount, you would need to change both occurences of 99 (one at the beginning and one at the end).

Edit: I think I should explain how it works. I circumvent the fact that I can't recurse a function if it's not named by creating an anonymous function, which takes an anonymous function as a parameter and calls it, passing it as an argument. Then it's just string formatting and neat little if-clauses built by using tuples and selecting the value with a boolean. Furthermore, I used c or "no more" to select c if it's greater than 0 and otherwise "no more".

Edit 2: Seems like I missed some pretty big things like multiplying strings with booleans instead of ("","text")[bool] and the fact that strings are iterable (("n","N")[p] -> "nN"[p])

seequ

Posted 15 years ago

Reputation: 1 714

1

Scala, 290

def b(i:Int,j:Int)=(i+" bottle"+(if(i==1)""else"s"))+(if(j==1)" of beer on the wall"else"");(1 to 99).reverse.map{i => b(i,1)+", "+b(i,0)+" of beer.\n"+(if(i == 1) "Go to the store and buy some more, "+b(99,1)+"."else"Take one down and pass it around, "+b(i-1,1)+".\n")}.foreach{println(_)}

Lalith

Posted 15 years ago

Reputation: 251

1

Python (284 chars)

o=1;b,w,f,s,l='bottle%s of beer|on the wall|%d %s %s, %d %s.\n|Take one down and pass it around, %d %s %s.\n\n|Go to the store and buy some more, 99 %s %s.\n'.split('|');c='s';d='';j=99;k='';i=j
while i>o:
 k+=f%(i,b%c,w,i,b%c)+s%(i-o,b%c,w)
 i-=o
k+=f%(o,b%d,w,o,b%d)+l%(b%c,w);print k,

Thomas O

Posted 15 years ago

Reputation: 3 044

1

C

#define $ " bottles of beer"
#define _ $" on the wall"
main(t){for(t=99;t;printf("%d"_", %d"$".\n",t,t),printf(t?"Take one down and pass it around, %d"_"\n":"Go to the store and buy some more, 99"_"\n",t---1));}

(NOTE: should compile fine "as is" in gcc, however due to the t-- undefined behavior, on vs one must replace "t?" with "t>1?", 2 bytes longer =;)

David

Posted 15 years ago

Reputation: 141

If it is indeed undefined (and not implementation-defined) behavior then one should treat the whole program as just accidentally doing what you intended. – Joey – 14 years ago

1

C#, 289 286 275 274 characters

Didn't do anything creative, just tried to make it small.

Update: I've taken a different approach and shaved off another 11 12 characters. Still thinking about it... haven't given up and googled it yet.

class 
P{static 
void Main(){
for(int i=99;i>0;
)System.Console.Write
(i+"{1}{2}{3}, {0}{1}{2} of beer.\n"+(i>1?
"Take one down and pass it around, {4}{1}{5}{3}.\n\n":
"Go to the store and buy some more, 99{1}s{3}."
),i--," bottle",i>0?"s":"",
" of beer on the wall"
,i,i>1?"s":""
);}}

Earlier version:

class P{
static void 
Main(){for(int 
i=99;i>0;){string a
=" bottle",b=" of beer",c=
" on the wall",e=i+a+(i>1?"s":"")+
b;System.Console.Write(e+c+", "+e+".\n"+(i-->
1?"Take one down and pass it around, "+i+a+(i>1?"s":"")+b
+c+".\n\n":"Go to the store and buy some more, 99"+a+"s"+b+c+"."));}}}

Igby Largeman

Posted 15 years ago

Reputation: 353

Good job, and keep going. This can be done in 232 chars in C#. – nharren – 14 years ago

This might help: link

– nharren – 14 years ago

Oh man, 232? Now I'm gonna have to keep working on it. Will that link give me the answer? I want to try to figure it out myself first. – Igby Largeman – 14 years ago

No it is just a hint. – nharren – 14 years ago

You can take the braces off the for loop. – nharren – 14 years ago

You must have added that comment while I was editing it to do exactly that. :) Still a long way to go to 232. I gotta stop thinking about this at work though. – Igby Largeman – 14 years ago

1

C - 297 characters

My first golfing attempt! The only "bug" I can think of is that it prints a double \n for the final sentence too. A few characters could be saved if the C preprocessor could have substituted macros inside printf strings, but apparently it can't.

#include <stdio.h>
#define y a,i-1?"s":""
main(){int i;char*a=" bottle",*b=" of beer",*c=" on the wall";for(i=99;i!=0;i--)printf("%d%s%s%s%s, %d%s%s%s.\n%s, %d%s%s%s%s.\n\n",i,y,b,c,i,y,b,i-1?"Take one down and pass it around":"Go to the store and buy some more",i-1?i-1:99,a,i?"s":"",b,c);}

djJack

Posted 15 years ago

Reputation: 11

1

C++

Uses recursion.

#include <iostream>
using namespace std;
void f(int n)
{
    if(n==0)
    {
        cout<<"Go to the store and buy some more, 99 bottles of beer on the wall.";
    }
    else
    {
        if(n==94)cout<<"....\n\n";
        else if(n>94||n<4)
            cout<<n<<" bottles of beer on the wall, "<<n<<" bottles of beer.\nTake one down and pass it around, "<<n-1<<" bottles of beer on the wall.\n\n";
        f(n-1);
    }
}
int main()
{
f(99);
return 0;
}

bacchusbeale

Posted 15 years ago

Reputation: 1 235

1

C++

#include<iostream>

using namespace std;

int f(int n)
{
    if(!(n-1))
    { 
        cout<<"Take one down and pass it around, 1 bottle of beer on the wall."<<endl<<endl;

        cout<<"1 bottle of beer on the wall, 1 bottle of beer."<<endl;
        cout<<"Go to the store and buy some more, 99 bottles of beer on the wall."<<endl<<endl; 
        return 0;
    }

    n!=99 && cout<<"Take one down and pass it around, "<<n <<" bottles of beer on the wall."<<endl<<endl;
    cout<<n<<" bottles of beer on the wall, "<< n<< " bottles of beer. "<<endl;

    return f(--n);
}   

int main()
{
    f(99);
    return 0;
}

Furqan

Posted 15 years ago

Reputation: 11

1

QBasic - Runs in MS-DOS 6.22

DATA "abdefghiklmnoprstuwy ,."
DATA 6,2,4,1,1,2,3,4,4,3,4,3,4,2,6,2,2,5,3,4,4,1,1
DATA 2,13,17,17,10,4,13,5,2,4,4,15,21,16,13,12,17,7,4,19,1,10,10,-17,1,9,4,13,12,4,3,13,19,12,1,12,3,14,1,16,16,8,17,1,15,13,18,12,3,-6,13,17,13,16,17,13,15,4,2,18,20,16,13,11,4,11,13,15,4,22,23
DATA 7,6,6,13,15,1,1
DATA 4,1,5,4,2,4,3
DATA 4,1,4,2,4,3
DATA 4,6,4,7,4,8
DATA 9,4,10,4,11,4,12,4,13,4,14,4,15
DATA 16,4,17,4,7,4,18,4,12,4,19,4,20,4,21
DATA 22
DATA 23

READ l$
DIM z$(LEN(l$))
DIM x%(LEN(l$))
DIM u%(7)
m% = 1

FOR y% = 1 TO UBOUND(x%)
        READ x%(y%)
NEXT y%

FOR y% = 1 TO 6
        m% = m% * x%(y%)
NEXT y%

m% = m% + x%(y%)

FOR y% = 1 TO UBOUND(z$)
        FOR w% = 1 TO x%(y%)
                READ v%
                IF v% > 0 THEN
                        z$(y%) = z$(y%) + MID$(l$, v%, 1)
                ELSE
                        z$(y%) = z$(y%) + UCASE$(MID$(l$, -1 * v%, 1))

                END IF
        NEXT w%
NEXT y%

FOR y% = 1 TO UBOUND(u%)
        READ u%(y%)
NEXT y%

FOR y% = 1 TO UBOUND(u%)
        FOR w% = 1 TO u%(y%)
                READ v%
                s$(y%) = s$(y%) + z$(v%)
        NEXT w%
NEXT y%

FOR i% = m% TO 1 STEP -1

        IF i% > 2 THEN
                PRINT STR$(i%) + s$(1) + s$(3) + s$(6) + STR$(i%) + s$(3) + s$(7)
                PRINT s$(4) + s$(6) + STR$(i% - 1) + s$(1) + s$(3) + s$(7)
        ELSEIF i% = 2 THEN
                PRINT STR$(i%) + s$(1) + s$(3) + s$(6) + STR$(i%) + s$(1) + s$(7)
                PRINT s$(4) + s$(6); STR$(i% - 1) + s$(2) + s$(3) + s$(7)
        ELSE
                PRINT STR$(i%) + s$(2) + s$(3) + s$(6) + STR$(i%) + s$(2) + s$(7)
                PRINT s$(5) + s$(6) + STR$(m%) + s$(1) + s$(3) + s$(7)
        END IF

        PRINT ""
NEXT i%

Kibbee

Posted 15 years ago

Reputation: 919

1

LaTeX / PGF

Using (almost) only the new logic facilities of the PGF/TikZ project:

\documentclass[twocolumn]{article} % Use twocolumn option to ... um ... save paper
\usepackage{tikz}
\usepackage{fmtcount}

\begin{document}
\pgfkeyssetvalue{/singular/0}{s}
\pgfkeyssetvalue{/singular/1}{}

\pgfkeys{/text/1/.code={\numberstringnum{#1}}}
\pgfkeys{/text/0/.code={no more}}

\foreach \x in {99, 98 , ..., 1} {
  \pgfmathequalto{\x}{1}
  \noindent
  \Numberstringnum{\x} bottle\pgfkeys{/singular/\pgfmathresult} of beer of the wall,\\
  \numberstringnum{\x} bottle\pgfkeys{/singular/\pgfmathresult} of beer.\\
  Take one down pass it around,\\
  \pgfmathtruncatemacro{\y}{\x - 1}
  \pgfmathgreaterthan{\y}{0}
  \pgfkeys{/text/\pgfmathresult=\y}\pgfmathequalto{\y}{1}
    bottle\pgfkeys{/singular/\pgfmathresult} of beer on the wall.\\
  \\
}

\end{document}

Joel Berger

Posted 15 years ago

Reputation: 2 261

that language seems pretty hard to write, to do "\" in my keyboard I must click ctrl + alt + <another key> – ajax333221 – 14 years ago

I don't know about your keyboard, but no, doing logic in LaTeX is not simple. – Joel Berger – 14 years ago

1

Not the shortest, but an attempt to use the most extraordinary Duff's Device.

#include <stdio.h>

void print_beer(int *n)
{
    printf("%d bottles of beer on the wall, %d bottles of beer.\n", *n, *n);
    --*n;
    printf("Take one down and pass it around, %d bottle%s of beer on the wall.\n\n", *n, *n > 1 ? "s" : "");
}

void beer(int n)
{
    switch (((n - 1)) % 7) {
        case  0:   do { print_beer(&n);
        case  6:        print_beer(&n);
        case  5:        print_beer(&n);
        case  4:        print_beer(&n);
        case  3:        print_beer(&n);
        case  2:        print_beer(&n);
        case  1:        print_beer(&n);
                   } while (n - 6 > 0);
    }
}

int main(void)
{
    int n = 99;

    beer(n);
    printf("1 bottle of beer on the wall, 1 bottle of beer.\n");
    printf("Go to the store and buy some more, %d bottles of beer on the wall.\n", n);

    return 0;
}

Jean-Marc Montjean

Posted 15 years ago

Reputation: 11

1

Python 3.2 (256)

import sys
a,b,c,d=" bottles of beer"," on the wall","1 bottle of beer",".\n"
[print(str(i)+a+b+', '+str(i)+a+d+'Take one down and pass it around, '+str(i-1)+a+b+d) for i in range(99,1,-1)]
print(c+b+', '+c+d+'Go to the store and buy some more, 99'+a+b+d)

Readability sucks though. :|

l0nwlf

Posted 15 years ago

Reputation: 61

1

Python with recursivity...

q=lambda e:' bottle%s of beer '%e
w='on the wall'
r='s'
def b(x):
    if x==1:
        print'1%s%s, 1%s\nGo to the store and buy some more, 99%s%s'%(q(''),w,q(''),q(r),w)
    else:
        print'%s%s%s, %s%s\nTake one down and pass it around, %s%s%s'%(x,q(r),w,x,q(r),x-1,q(r),w)
        b(x-1)
b(99)

Gus

Posted 15 years ago

Reputation: 111

1

F#, 280 bytes

let p,w=printfn," on the wall"
let a n=sprintf"%d bottle%s of beer"n (if n=1 then""else"s")
let rec f=function 1->p"Go to the store and buy some more, %s%s."(a 99)w|n->p"Take one down and pass it around, %s%s.\n"(a(n-1))w;g(n-1)
and g n=let b=a n in p"%s%s, %s."b w b;f n
g 99

Somewhat decompressed version:

let printfunc = printfn

let wallstring = " on the wall"

let inventory n = sprintf "%d bottle%s of beer" n (if n=1 then "" else "s")

// let rec..and signifies mutual recursion. Without the 'and' keyword
// nextaction won't know about displaybeers which is defined later.
let rec nextaction = function
    | 1 -> // oh noes! last bottle!
        printfunc "Go to the store and buy some more, %s%s." (inventory 99) wallstring
    | n -> // keep guzzling!
        printfunc "Take one down and pass it around, %s%s.\n" (inventory (n-1)) wallstring
        displaybeers (n-1)

and displaybeers n = 
    let beerstring = inventory n
    printfunc "%s%s, %s." beerstring wallstring beerstring
    nextaction n

// let's have a party
displaybeers 99 

cfern

Posted 15 years ago

Reputation: 311

1

C++

Why output to the console when you can output error messages?

main.cpp:

#include "99.h"
int main(){return 0;}

99.h:

#error 99 bottles of beer on the wall...
#include "98.h"

98.h:

#error 98 bottles of beer on the wall...
#include "97.h"

This is continued all the way through 1.h:

#error 1 bottle of beer on the wall...

When the programmer tries to compile it, the compiler outputs the error message

99 bottles of beer on the wall...

The programmer then removes the #error statement and recompiles the program, getting the error message

98 bottles of beer on the wall...

Eventually this outputs the entire song.

Lucas

Posted 15 years ago

Reputation: 665

1

Q, 245

{-1(-3!x),b,$[x=1;e;d],a,", ",(-3!x),b,$[x=1;e;d]," of beer.\n",$[x=1;"Go to the store and buy some more, ";"Take one down and pass it around, "],(-3!$[x=1;99;x-1]),(b:" bottle"),$[x=2;e:"";d:"s"],(a:" of beer on the wall"),".";}each(99-til 99);

tmartin

Posted 15 years ago

Reputation: 3 917

1

PHP - 176

My implementation has some null bytes or other random "?" characters, so I wrote a wrapper around it to show how to get the string, as well as the total characters output:

$string = gzdeflate('$a=" bottle";$b=" of beer";$c=" on the wall";for($i=99;$i>1;)echo"$i{$a}s$b$c, $i{$a}s$b.\nTake one down and pass it around, ".--$i.$a."s$b$c.\n\n";echo"$i$a$b$c, $i$a$b.\nGo to the store and buy some more, 99{$a}s$b$c.";');
$total  = strlen($string);
$total += strlen("eval(gzinflate(''))");

echo 'Total characters: '.$total."\n\n\n";
eval(gzinflate($string));

syntaqx

Posted 15 years ago

Reputation: 131

1

Vitsy, 273 227 Bytes

Most Recent Update

&".reeb fo selttob "?b9*D1-\[1m4m2maO"dnuora ti ssap dna nwod eno ekaT"6m4m2maO1-]DN3m{?5m4m3mDO{?aO" ,erom emos yub dna erots eht ot oG"6mXb9*1m"."OaO
DN?l1-\[DO{]{?5m
?l\[DO{]?
?7\[DO{]{8\[DO{]
" ,"OODN
"llaw eht no "6m
l1-\O

This basically does the same thing as the old method, the difference being that commonly used functions are moved to separate lines. Then, those lines are called and executed with m, where the number preceding tells the instruction pointer which line to go to. Once that line finishes, it'll go back to where m was last called.

Old Method

This is a bit complex. Method is in the code block.

&".reeb fo selttob "?9b*D1-\[DN?l1-\[DO{]{?" ,llaw eht no "l1-\ODN?l\[DO{]?aO" ,dnuora ti ssap dna nwod eno ekaT"l1-\ODN?l\[DO{]?1-aO]DN?7\[DO{]{8\[DO{]{?" ,llaw eht no "l1-\ODN?7\[DO{]{9\[DO{]?aO"99 ,erom emos yub dna erots eht ot oG"l1-\O?l1-\[DO{]{?".llaw eht no "l1-\O
&               Instantiate a new stack.
 ".reeb fo selttob "    Push " bottles of beer." to the current stack.
                    ?     Rotate to the next stack.
                     9b*    Push 99 to the stack.
                        D1-\[...]     Do everything in the top set of brackets 98 times.
                             DN       Duplicate the top item of the stack and output it as a number.
                               ?       Rotate a stack - this contains " bottles of beer."
                                l1-\[DO{]      Print it out (except for the period), but don't remove any items.
                                         {       Rotate the current stack - this skips the period.
                                          ?       Rotate back to the original stack.
                                           " ,llaw eht no "l1-\O   Push " on the wall, " to the stack, then print it out.
                                                                DN   Print out the top item of the stack as a number.
                                                                  ?    Rotate to the next stack.
                                                                   l\[DO{]     Print it all out, but don't remove any items.
                                                                          ? Rotate to the next stack (top stack again).
                                                                           aO    Print a newline.
                                                                             " ,dnuora ti ssap dna nwod eno ekaT"l1-\ODN  Push "Take one down and pass it around, " to the stack and print it out.
                                                                                                                        ?  Rotate to the next stack.
                                                                                                                         l\[DO{]  Print out everything in the stack, but don't remove anything.
                                                                                                                                ?  Rotate to the next stack.
                                                                                                                                 1-  Subtract one from the top item of the stack.
                                                                                                                                   aO  Print a newline.
                                                                                                                                     ]  End the main loop.
                                                                                                                                      DN  Duplicate the top item of the stack and print it out.
                                                                                                                                        ?7\[DO{]{8\[DO{]{?  Print out the next stack over (the one holding " bottles of beer.", but skip the period and the "s".
                                                                                                                                                          " ,llaw eht no "l1-\O  Push " on the wall, " to the stack and print it out.
                                                                                                                                                                               DN Duplicate the top item of the stack and print it out as a number.
                                                                                                                                                                                 ?7\[DO{]{9\[DO{]? Print out everything in the next stack except the period.
                                                                                                                                                                                                  aO Print a newline.
                                                                                                                                                                                                    "99 ,erom emos yub dna erots eht ot oG"l1-\O  Push "Go to the store and buy some more, 99" to the stack and print it out.
                                                                                                                                                                                                                                                ?l1-\[DO{]{? Move over a stack, print everything out but the ".".
                                                                                                                                                                                                                                                            ".llaw eht no "l1-\O  Push " on the wall." to the stack, then print it out.

Addison Crump

Posted 15 years ago

Reputation: 10 763

This isn't code-golf; you don't need to list byre count. – lirtosiast – 10 years ago

@ThomasKwa I wrote it for the purpose of code-golfing, though - even though the competition was aimed at pop-con, I wrote the post aimed mostly at code-golfing. Mostly to see how short I could make it. :D – Addison Crump – 10 years ago

1

node/javascript - 180

b=' bottles of beer';w=' on the wall';i=99;while(i)console.log(i+b+w+', '+i+b+'\n'+(!--i?'Go to the store and buy some more, 99':'Take one down and pass it around, '+i)+b+w+'.\n');

ericv

Posted 15 years ago

Reputation: 11

Could you add an explanation/an ungolfed version, please? – Addison Crump – 10 years ago

2Golfing tip: never use while(cond). It's the same length as for(;cond;), and you can nearly always take advantage of moving something into the initialisation and something into the update parts of the for to save at least one character each for a semicolon. – Peter Taylor – 10 years ago

0

for i in range(99,0,-1): r=", ";m=i-1;n=".\n";v='s';k=(v,'')[m<2];b=" of beer";w=" on the wall";a=" bottle";y=a+v+b;s=`i`+y+w+r+`i`+y+n+"Take one down and pass it around"+r+`m`+a+k+b+w+n;t=`i`+a+b+w+r+`i`+a+b+n+"Go to the store and buy some more, 99"+y+w+n;print (s,t)[i<2]

python one liner

hnzjo

Posted 15 years ago

Reputation: 101

1How about one line with no semi-colons? I'd +1 that. – primo – 13 years ago

0

SQL - 335 531

EDIT: removed XML and temporary table. Not MS SQL specific anymore.

Readable:

WITH c AS(
    SELECT LTRIM(99)n
 UNION ALL
    SELECT LTRIM(n-1)
    FROM c
    WHERE n>1
)
SELECT n+v+IIF(n=1,z,s)+t+u+', '+n+v+IIF(n=1,z,s)+t+p+r+
           IIF(n=1,b,a+LTRIM(n-1))+v+s+t+u+p+IIF(n=1,z,r)
FROM(SELECT 
    ' of beer't,
    ' on the wall'u,
    ' bottle' v,
    's's,
    '.'p,
    'Take one down and pass it around, 'a,
    'Go to the store and buy some more, 99'b,
    ''z,
    CHAR(13)r)w,c

Golfed:

WITH c AS(SELECT LTRIM(99)n UNION ALL SELECT LTRIM(n-1)FROM c WHERE n>1)SELECT n+v+IIF(n=1,z,s)+t+u+', '+n+v+IIF(n=1,z,s)+t+p+r+IIF(n=1,b,a+LTRIM(n-1))+v+s+t+u+p+IIF(n=1,z,r)FROM(SELECT ' of beer't,' on the wall'u,' bottle' v, 's's,'.'p,'Take one down and pass it around, 'a,'Go to the store and buy some more, 99'b,CHAR(13)r,''z)w,c

comfortablydrei

Posted 15 years ago

Reputation: 701

0

C Preprocessor (470)

There is very little actual C in this answer, just lots of horrible preprocessor heresy.

Why use function recursion when you can use/abuse FILE RECURSION?

Only works with gcc (or any other C compiler that has a __COUNTER__ macro). The filename must be "s.c".

#if !__COUNTER__
#define s(i) i==1?"":"s"
main(){
int i;
#endif
#if __COUNTER__<301
i=100-__COUNTER__/3;
printf("%d bottle%s of beer on the wall, %d bottle%s of beer\n"
#if __COUNTER__==299
"Go to the store and buy some more"
#define j 99
#else
"You take one down, pass it around"
#define j i-1
#endif
", %d bottle%s of beer on the wall.\n\n",i,s(i),i,s(i),j,s(i-1));
#include "s.c"
#else
}
#endif

ApproachingDarknessFish

Posted 15 years ago

Reputation: 951

0

JavaScript (using console) 241 235

for(l=console.log,i=99,z=(y="bottle")+"s",x=" of beer",w=" on the wall";0<i;i--)j=i-1,c=1!=i?z:y,k=1!=j?z:y,l(i+" "+c+x+w+",\n"+i+" "+c+x+",\nTake one down, pass it around,"),l(0!=j?j+" "+k+x+w+".":"Go to the store and buy some more!")

Some serious abuse of comma operators, bracketless logic and string re-use...

Next iteration, shifted console.log into for definition and shrunk by 6 bytes

WallyWest

Posted 15 years ago

Reputation: 6 949

This fails to provide the last verse with "no more bottles of beer on the wall, no more bottles of beer..." – Már Örlygsson – 11 years ago

According to the OP, the last verse actually should say "Go to the store and buy some more, 99 bottles of beer on the wall..."

Which is it? ;) – WallyWest – 11 years ago

You're right, OP had the last verse like that. (I was referring to the de-facto "official" version here: http://99-bottles-of-beer.net/lyrics.html)

– Már Örlygsson – 11 years ago

0

bash (+ sed) 254 224 chars

This recreate exactly question sample, start, indentation and end. Don't do infinite loop.

The only transgression of the rules imposed is due to the fact that I prefer not to promote alcohol! (used word has same length)

for((n=99;n>0;n--));do printf -v s "%$[n>1]s";echo $n" bottle${s// /s} of milk"{" on the wall"{$'.\n\n',","},.};[ $n -gt 1 ]&&printf "Take one down and pass it around, "||printf "Go to the store and buy some more, ";done|sed '1{x;N;d};s/^ //;${G;s/\n//}'

for((n=100;n-->1;));do((n>1))&&s=s||s=;echo "$n bottle$s of milk"{' on the wall'{$'.\n\n',\,},.};done|sed '1{x;N;d};s/^ //;${G;s/\n/\nGo to the store and buy some more, /;p;d};/wall.$/s/^/Take one down and pass it around, /'

or more readable:

for (( n=100;n-->1 ;-O))
do
    ((n>1)) && s=s || s=
    echo "$n bottle$s of milk"{' on the wall'{$'.\n\n',\,},.}
  done |
    sed '
         1 {
             x;
             N;
             d;
           };
         s/^ //;
         $ {
             G;
             s/\n/\nGo to the store and buy some more, /;
             p;
             d;
           };
         /wall.$/s/^/Take one down and pass it around, /;
        ';

There are some added characters :-O, but only for cosmetic ;-)

Adding this small filter:

| sed -rne '1,5p;10s/^.*$/.\n.\n\./p;11,${H};${x;s/^.*\n(([^\n]*(\$|\n)){6})/\1/p}'

will just dump:

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

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

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

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

F. Hauri

Posted 15 years ago

Reputation: 2 654

0

Zozotez LISP

Considering Zozotez doesn't support numbers nor strings writing 99 bottles seemed like a challenge. The numbers are consisting of symbols and to count down I use lists for each digit. To run this BrainFuck cell size need to be larger than one byte. Jitbf has 32 bit cell sizes and runs it reasonably fast, but even it becomes exponentially slow as Zozotez uses memory further and further to the right of the work cells and it does not have garbage collection.

;; Run with jitbf zozotez.bf < bottles.zzt
((\ ()
   ;; data types to resemble
   ;; digits
   (:'9 '(9 8 7 6 5 4 3 2 1 0))

   ;; the two digits
   (:'1s 9)
   (:'10s '(9 8 7 6 5 4 3 2 1))

   ;; not
   (:'not
    (\ (x)
       (? x NIL T)))

   ;; alias if as a two way and (we have macros too)
   (:'and ?)

   ;; prints the number of bottles
   (:'print
    (\ ()
      (? 10s (p (a 10s) ()))
      (p (a 1s) ())))

   ;; decreases the number of bottles
   (:'next 
    (\ ()
      (? (d 1s)
         (:'1s (d 1s))
         ((\()
            (:'1s 9)
            (? 10s
               ((\()
                  (:'10s (d 10s))
                  (? (s 10s)
                     (:'1s '(9 8 7 6 5 4 3 2 1 no))
                      T)))))))))

   ;; The main loop of the program
   (:'loop 
    (\ ()
      (? (and (s 10s) (not (d 1s))) (p'No()) (print))
      (p '| bottles of beer on the wall, |())
      (print)
      (p '| bottles of beer.|)
      (? (next)
         ((\ ()
            (p '|Take one down and pass it around, | ())
            (print)
            (p '| bottles of beer on the wall.
|)
             (loop)))
         (p '|Go to the store and buy some more, 99 bottles of beer on the wall.
|))))

   ;; start 
   (loop)))

This is designed to work without a driver (REPL) so it is one expression by executing a anonymous function that has explicit begin.

Here's the beginning and the end of the output:

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.

...

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

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

Heres the result of time with jitbf on my Quad Xeon running constant at 2,7Ghz:

900.66user 0.00system 15:01.14elapsed 99%CPU (0avgtext+0avgdata 8076maxresident)k
1872inputs+0outputs (2major+2222minor)pagefaults 0swaps

Sylwester

Posted 15 years ago

Reputation: 3 678

0

C# (298 294)

using System;class P{static void Main(){Func<int,string>f=(i)=>{return i+" bottle"+(i>1?"s":"")+" of beer";};for(int i=99;i>0;i--)Console.Write("{0} on the wall, {0}.\n"+(i>1?"Take one down and pass it around":"Go to the store and buy some more")+", {1} on the wall.\n\n",f(i),f(i>1?i-1:99));}}

RobIII

Posted 15 years ago

Reputation: 397

0

I recently found this:

Black and red border, vertical multicolored lines

I haven't tested it though.

Pureferret

Posted 15 years ago

Reputation: 960

A hint to what language it is would have been useful. Is this Piet example from you? Apparently it isn’t? Where did you get it from? – M L – 10 years ago

0

Python:

a=99
while a:
    print          `a`+" bottle"+("s","")[a==1]+" of beer on the wall, ",
    print          `a`+" bottle"+("s","")[a==1]+" of beer."
    if a-1: print  "Take one down and pass it around, " +`a-1`+ " bottles of beer on the wall"
    else: print    "Go to the store and buy some, more 99 bottles of beer on the wall."
    print
    a-=1

Not very interesting and slightly golfed, but I thought I'd post it anyways.

ɐɔıʇǝɥʇuʎs

Posted 15 years ago

Reputation: 4 449

0

MS Excel (14,683bytes)

MS Excel 2003, saved in .xlsx format (14,683 bytes) (is this really "programming") https://www.dropbox.com/s/40v2byau92ifka9/99bottles4.xlsx

Tim

Posted 15 years ago

Reputation: 101

"is this really "programming"" - no, unless you used VBA to fill out the data :) – Nate Koppenhaver – 14 years ago

0

Erlang - 326

-module(d).
-export([b/1]).
b(1)->io:format("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."),b(99);b(B)->C=B-1,io:format("~p bottles of beer on the wall, ~p bottles of beer.~nTake one down and pass it around, ~p bottles of beer on the wall.",[B,B,C]),b(C).

POSIX_ME_HARDER

Posted 15 years ago

Reputation: 101

0

Julia

colon(x,y::String,z)=replace(x,y,z);print(join(map(x->"PA, PB.\nC, $(x-1)A.\n\n":"P":"$x",5:-1:1)):"C, 0":"D, 99":"A":"B on the wall":"B":" bottles of beer":"C":"Take one down and pass it around":"D":"Go to the store and buy some more")

Didn't try to be visually creative, but to make it use an interesting syntax. Overloaded ternary range operator!

Glen O

Posted 15 years ago

Reputation: 2 548

0

PHP - first time there :)

<?php

$b = "bottles of beer";
$bw = "$b on the wall";
$t = "Take one down and pass it around,";
$cnt = 99;

     while(true)
     {
        echo "$cnt $bw, $cnt $b.\n";
        $cnt--;
        if ($cnt==0) break;
        echo "$t $cnt $bw.\n\n";
     }

     echo "Go to the store and buy some more, 99 $bw.\n\n";

?>

vitaly

Posted 15 years ago

Reputation: 1

11 bottles of beer on the wall? – boothby – 14 years ago

0

Here. First time post. JAVA

public static void main(String [] args){
for(int i = 99; i>=2; i--){

    System.out.println(i + " bottles of beer on the wall, "+i+" bottles of beer. "
            + "\n Take one down and pass it around, "+(i-1)+" bottles of beer on the wall.\n");

}
 System.out.println("1 bottle of beer on the wall, 1 bottle of beer."
                   + " \n Go to the store and buy some more, 99 bottles of beer on the wall.");
}

Mob

Posted 15 years ago

Reputation: 191

0

Python

i=99
while i>0:
 k,b,o="%s bottles"," of beer"," on the wall"
 if i==1:k=k[:9]+k[10:]
 '%s, %s.'%(k+b+o,k+b)%(i,i)
 if i!=1:'Take one down and pass it around, %s'%x[:31]%(i-1)
 i-=1
else: 'Go to the store and buy some more, %ss%s.'%(k,o)%99

Umur Kontacı

Posted 15 years ago

Reputation: 101

How do you run it? I get “NameError: name 'x' is not defined” with both Python 2 and 3. – manatwork – 13 years ago

1what language is this? – Nate Koppenhaver – 14 years ago

It is Python. http://www.python.org

– Umur Kontacı – 14 years ago

0

PHP (172)

for($i=99;$i>0;$i--){$s=($i>0)?'s':'';echo "$i bottle$s of beer on the wall, $i bottle$s of beer.\nTake one down and pass it around, $i bottle$s of beer on the wall.\n\n";}

tobius

Posted 15 years ago

Reputation: 161

0

Scala (247 265 chars)

Fairly new to Scala, so I wanted to see how compressed I could get it.

Edit: Added ${if(a>2)"s"else""} to address special case of 1 bottle remaining.

Compressed version:

val(b,o,w)=(" bottle"," of beer"," on the wall");for(a<-99 to(1,-1))if(a>1)println(f"$a${b}s$o$w, $a${b}s$o.\nTake one down and pass it around, ${a-1}$b${if(a>2)"s"else""}$o$w.\n")else print(f"$a$b$o$w, $a$b$o.\nGo to the store and buy some more, 99${b}s$o$w.\n")

Expanded:

val(b,o,w)=(" bottle"," of beer"," on the wall");
for(a<-99 to(1,-1))
  if(a>1)
    println(f"$a${b}s$o$w, $a${b}s$o.\nTake one down and pass it around, ${a-1}$b${if(a>2)"s"else""}$o$w.\n")
  else
    print(f"$a$b$o$w, $a$b$o.\nGo to the store and buy some more, 99${b}s$o$w.\n")

randak

Posted 15 years ago

Reputation: 141

Your code is nice, but it outputs "2 bottles of beer ... pass it around, 1 bottles of ..." The question says that it should say 'bottle', not 'bottles'. – ProgramFOX – 11 years ago

Good catch. I'll take a look at that. – randak – 11 years ago

0

C# (271 Characters)

class P{static void Main(){string b=" bottle",w=" on the wall",o=" of beer",p=".\n",z;for(int i=99;i>0;)System.Console.Write((z=i+b+(i>1?"s":"")+o)+w+", "+z+p+(i-->1?"Take one down and pass it around, "+i:"Go to the store and buy some more, 99")+b+(i>1?"s":"")+o+w+p);}}

ICR

Posted 15 years ago

Reputation: 211

0

Delphi (349)

program B;{$APPTYPE CONSOLE}const c=' of beer on the wall';d:array[Boolean]of string=(' bottles', ' bottle');var i:Byte;begin for i:=99downto 1do begin WriteLn(i,d[i=1],c,', ',i,d[i=1],' of beer.');if i>1then WriteLn('Take one down and pass it around, ',i-1,d[i<3],c,'.'#13#10)else Write('Go to the store and buy some more, 99',d[1=2],c,'.')end;end.

The_Fox

Posted 15 years ago

Reputation: 101

0

Python 3 (not really golfed, just a bit creative)

b=lambda n:'%d bottl%s of beer'%(n,n>1and'es'or'e')
any(map(print,(((2*'%s, %s on the wall, %s.\n')[4:42]+'.\n')%(2*(b(i),)+(i>1and('Take one down and pass it around',b(i-1))or('Go to the store and buy some more',b(99))))for i in range(99,0,-1))))

etuardu

Posted 15 years ago

Reputation: 141

0

PHP 132 chars =]

    $e='bottles of beer';$x='on the wall';$i=100;while($i>0)echo"$i $e $x, $i $e.
Take one down and pass it around,  ".--$i." $e $x.

";

Korvin Szanto

Posted 15 years ago

Reputation: 121

Go to the store and buy some more, 99 bottles of beer on the wall.? – Gareth – 14 years ago

I didn't read that until it was too late =[ – Korvin Szanto – 14 years ago

0

C# - 324

using System;class b{ static void Main(){for(int i=99;i>1;i--){Console.WriteLine("{0} bottles of beer on the wall, {0} bottles of beer,\n"+"take one down, pass it around...\n", i);}Console.WriteLine("1 bottle of beer on the wall, 1 bottle of beer,\n"+"go to the store and buy some more, 99 bottles of beer on the wall!");}}

syrinx_

Posted 15 years ago

Reputation: 101

0

256 1Lang

Written in 1Lang that I made for another codegolf.

https://codegolf.stackexchange.com/a/25150

:b" of beer"
:w" on the wall"
:t"Take one down and pass it around, "
:s"Go to the store and buy some more, "
:c", "
:n".\n"
@Bx{?=x0{+"No more bottles"b}{+x+" bottle"+?=x1{""}{"s"}b}}
@Fx{?=x0{+B0+w+c+B0+n+s+B99+wn}{+Bx+w+c+Bx+n+t+B-x1+w+n+"\n"F-x1}}
F99

philcolbourn

Posted 15 years ago

Reputation: 501

0

JavaScript (232 bytes)

This one prints out the "official" version of the song as shown here: http://99-bottles-of-beer.net/lyrics.html - with "no more bottles of beer on the wall..." as the last verse.

for(o,e,n=100,t=" on the wall";n-->-1;)o=e+t+", "+e+".<br>"+(n>-1?"Take one down, pass it around, ":"Go to the store and buy some more, ")+(e=(0>n?99:n||"no more")+" bottle"+(1!=n?"s":"")+" of beer")+t+".<p>",99>n&&document.write(o)

Proof: http://codepen.io/anon/pen/DCyge

Már Örlygsson

Posted 15 years ago

Reputation: 101

0

Python: 233

p,i='bottle','beer'
n,t=p+"s of "+i,'on the wall'
for c in range(99,1,-1): print c,n,t+",",c,n+".\nTake one down and pass it around,",c-1,n,t+".\n"
print 1,p,"of",i,t+",",1,p,"of",i+".\nGo to the store and buy some more,",99,n,t+"."

nettux

Posted 15 years ago

Reputation: 101

0

C# - 304 significant characters.

Left this way to make it a little bit more readable, but it is 304 when all non-essential whitespace is removed.

string[] s = { "{0} {2}{3} {5}{6}, {0} {2}{3} {5}.\n", 
               "Take one down, pass it around, {1} {2}{4} {5}{6}.\n", 
               "Go to the store and buy some more, 99 {2}{4} {5}{6}." };
Func<int, string> t = e => e !=1 ? "s" : "" ;
for (int i = 99; i > 0; i--)
    Console.WriteLine(
         s[0] + s[i > 1 ? 1 : 2], 
         i, i - 1, 
         "bottle", t(i), t(i-1), "of beer", " on the wall");

Andrew Backer

Posted 15 years ago

Reputation: 101

0

PYTHON

for x in xrange(99,0,-1):
    print('.\n\n'.join(('%(b)s on the wall',)*(2-x/99))+', %(b)s.\n%(c)s')%{'b':'%s bottle%s of beer'%(x,x-1 and's'or ''),'c':('Take one down, pass it around,','Go to the store and buy some more, 99 bottles of beer on the wall.')[(100-x)/99]},

nosklo

Posted 15 years ago

Reputation: 101

0

Java

package torento;


public class Beer {
    public static void main(String args[]) {
        int num;
        String word="bottles";

        for(num=99;num>0;num--)  
        {
            if(num==1) break;
            System.out.println(num + " " + word + " of beer on the wall, " + num + " " + word + " of beer");
            num=num-1;
            System.out.println("Take one down, pass it around, " + num + " " + word + " of beer on the wall");
            System.out.println( );
            num++;
        }
        System.out.println(num + " bottle of beer on the wall, " + num + " bottle of beer");
        System.out.println("Take one down pass it around, no more " + word + " of beer on the wall");
        System.out.println( );
        System.out.println("No more " + word + " of beer on the wall,no more bottles of beer");
        System.out.println("Go to the store and buy some more, 99 bottles of beer on the wall");

    }  
}

Anirudh Torento

Posted 15 years ago

Reputation: 1

0

My PHP implementation:

<?php
$i = 99;
$s = '{i} bottles of beer on the wall';
$r = 'Take one down and pass it around';
$f = 'Go to the store and buy some more';

while($i > 0) 
{    
    $sub = array('{i}' => &$i);

    if($i == 1)
        $sub['bottles'] = 'bottle';

    $sen = strtr($s, $sub);
    echo $sen, ', ', substr($sen, 0, strpos($sen, 'on')), PHP_EOL;

    if($i == 1)
        break;

    $i--;
    $sen = strtr($s, $sub);
    echo $r, ', ', $sen, PHP_EOL, PHP_EOL;
}    

$i = 99;
$sub = array('{i}' => $i); 
$sen = strtr($s, $sub);
echo $f, ', ', $sen, PHP_EOL;
?>   

phatskat

Posted 15 years ago

Reputation: 101

0

Ruby 1.9.2p0 -- 208 C

b="%d bottle%s of beer";99.downto(1){|n|s=b%[n,n>1?'s':''];a=n-1;puts s+" on the wall, "+s+(n>1?"\nTake one down and pass it around,#{b%[a,a>1?'s':'']}":"\nGo to the store and buy some more, #{b%[99,'s']}.")}

Rohit

Posted 15 years ago

Reputation: 193

0

Ocaml - Hope this counts as creative

open Printf

let display () =
   let language = ref 99 in
   let ocaml = "bottles of beer on the the wall, " in
   let joy = " bottles of beer." in
   let usage = "Take one down and " in
   let is = "pass it around, " in
   let recommended = " bottles of beer on the wall." in
   let what = "bottle of beer on the wall, " in
   let like = "bottle of beer." in
   let applauded = " bottle of beer on the wall." in
   while (!language > 1) do
      let say = (string_of_int !language) in
      let strongly = (string_of_int (!language - 1)) in
      printf "%s %s %s %s\n" say ocaml say joy;
      if (!language > 2) then
         printf "%s %s %s %s\n" usage is strongly recommended
      else 
         printf "%s %s %s %s\n" usage is strongly applauded;
      language:= !language - 1;
   done;
   let say = (string_of_int !language) in
   let the_end = "Go to the store and buy some more, 99 bottles of beer on the wall." in
   printf "%s %s %s %s\n" say what say like;
   printf "%s\n" the_end

Joseph Elcid

Posted 15 years ago

Reputation: 111

0

><>

(haven't seen it here)

4b9**1-&    v         >&::&4%:?!v4$-+v       >" bottle" v                                                            >", "v
    >&:&0(?;>&:&4%1=?;^         >~   >4,:n1=?^" bottles">" of beer">&1-:&4%1=                ?v" on the wall"&:&4%2=?^"."a>rv
 l?!^o02.                            >                                                                                      >
                                     ^r" ,dnuora ti ssap ,nwod eno ekaT"          v?=0,4&:-1&a<
                                              vr" ,erom emos yub ,erots eht ot oG"<
                                              > l?!vof3*1+5.
                                                   >4b9**faa++1.

See it swimming

JNF

Posted 15 years ago

Reputation: 131

0

Javascript (234)

o=' bottle',b=' of beer',s=o+'s'+b,w=' on the wall',t='.\nTake one down and pass it around, ',g='.\nGo to the store and buy some more, ',c=', ',i=99,n=i+s;while(i>1)print(n+w+c+n+t+(n=--i+o+[i>1?'s':'']+b));print(n+w+c+n+g+99+s+w+'.')

There is probably a way to reduce even further by avoiding the double print.

Ricardo Tomasi

Posted 15 years ago

Reputation: 131

0

CoffeeScript - 233

CoffeeScript is a bit hard to minify, but it's not bad:

b=' bottle';r=' of beer';w=' on the wall';t='Take one down and pass it around, ';g='Go to the store and buy some more, ';c=', ';i=100;x=1;(d=->x=--i+b+['s'if i>1]+r)();print x+w+', '+x+'\n'+(i>1&&t+d()+'\n'||--i||g+99+b+'s'+r)while i

Ricardo Tomasi

Posted 15 years ago

Reputation: 131

0

Python:-2.7

  x = 99
  for i in range(99):
    w = 'Take one down and pass it around, '+str((x-(i+1)))+' bottle of beer on the wall.'
    y = str((x-i))+' bottles of beer on the wall, '+str((x-i))+' bottles of beer'
    z = 'Go to the Store and buy some more, '+str(x)+' bottle of beer on the wall.'
    if i == (x-1):
        print(y + '\n' + z)
    else:
        print(y + '\n' + w)
    i += 1

Praneeth

Posted 15 years ago

Reputation: 111

0

Shell... -ish. (588 bytes)

1.sh: (I may have copied this wrong)

7z¼¯' ÐLÍÔ      L       ‘uÆ2 à|Äo:&²ÈdÀ*ny\0x&‚;9)—¹VûȶÃPÎ&,8íhÒ®•KˆŸ 挸‚þ­æ–qø½»£ß¯f¥¬–ö‘öÅÑ.“ã4Ys_  ZœI«±Ö™&ŧÇ1ìºØŽoÂM².űo¶ÖÀL”£S{¿U1SÑs:
qˆY)ŽJçXŽ”A<Œ£ãיּ•¤8³Æ,YyiA§Ékñ¾ËÊÃÆº-ý}aú€õìç½/%q)+F5U[ê(÷Áær2ì¡o$j~oÅ›ä
ƒ«¦‡tQS¦Ñÿ1l÷M‹8o¤Ù­¿ õ—n:¶‚^P—½Ìï¬î:¬l½¤ã-I߈†×C¨¬>³*Wù—Øü—ôÿ½Õ±ˆ·EÁª†Ýã9•Fü&ís_׫€è¼»‰XžEæ¥RcDႆ6
&¡#Å»G´ëˆ˜ìç3ˆ£(\¦ãw$¼Ìû#ýwç™*n-É{ÀßðBà

Û&M*0"èÙÔ™ýíuªŠ
g³¶YõñÊs©^AƒjÈh~JvöÖ®Ü<€N×ÇÌïìó½ÀþÉá
äàL²õD ‹U³°     Ô  #]   ®Ñ 
÷ɪU  
 1 . t x t   
 â#YäÐ       

2.sh:

mv 1.sh 1.7z

Lucas

Posted 15 years ago

Reputation: 665

0

AS2 - 159

a=99
b=" bottles of beer"
c=" bottle of beer"
d=" on the wall,"
e=", take one down and pass it around,"
while(a>0)
{
f=e+(a-1)+b+d
g=d+a
if(a<2)
    trace(a + c + g + c + f)
else
    trace(a + b + g + b + f)
--a
}

AS2 - 158 - Trimmed one off with a new if statement

a=99
b=" bottles of beer"
c=" bottle of beer"
d=" on the wall,"
e=", take one down and pass it around,"

while(a>0)
{
f=e+(a-1)+b+d
g=d+a
if(a<2?trace(a + c + g + c + f):trace(a + b + g + b + f));
--a
}

AS3 - 151 - Even shorter

a=99
o=" of beer"
f=" bottle"
d=" on the wall"
g=f+"s"+o
while(a)e=a^1?g:f+o,trace(a+e+d+", "+a+e+".\nTake one down and pass it around, "+--a+(a^1?g:f+o)+d)

chris w

Posted 15 years ago

Reputation: 1

0

VB11 (Creative Version)

Imports System.Runtime.CompilerServices
Module BottleSong
 Sub Main()
 Console.WriteLine(<Song>
<%= Iterator Function()
For i=99 To 0 Step -1:Yield i:Next
End Function().Select(Function(Bottles)<Verse>
<%= Bottles.OfBeer %> on the wall, <%= Bottles.OfBeer %>.
<%= If(Bottles > 0, "Take one down and pass it around", "Go to the store and buy some more") %>.
<%= (Bottles - 1).OfBeer %> on the wall,<%= (Bottles - 1).OfBeer %>.

</Verse>)%></Song>.Value)
 End Sub

<Extension()>Public Function OfBeer(Bottles As Integer) As XNode
    Bottles = If(Bottles < 0, 99, Bottles)
    Return <Bottles><%= Bottles %> bottle<%= If(Bottles <> 1, "s", "") %> of Beer</Bottles>
End Function
End Module

Exploiting some of vb.net features.

  • XML LIterals
  • Iterator Lambda
  • Extension Method

Adam Speight

Posted 15 years ago

Reputation: 1 234

0

Gema

bottle:*=* bottle@subst{\\X1\\X=\;\*=s;$0} of beer

line1:*=@bottle{*} on the wall, @bottle{$0}.\n
line2:*=Take one down and pass it around, @bottle{*} on the wall.\n\n

\A=@set{count;99}@repeat{98;@line1{${count}}@decr{count}@line2{${count}}}@line1{${count}}Go to the store and buy some more, @bottle{99} on the wall.\n@end

manatwork

Posted 15 years ago

Reputation: 17 865

0

jq

def bottle: "\( . ) bottle\( [0, ""][.] // "s" ) of beer";

def line1: "\( bottle ) on the wall, \( bottle ).\n";
def line2: . - 1 | "Take one down and pass it around, \( bottle ) on the wall.\n";
def linen: 99 | "Go to the store and buy some more, \( bottle ) on the wall.";

range(99; 0; -1) | line1 + if . == 1 then linen else line2 end

Run it with -n (null input) and -r (raw output) command line options.

manatwork

Posted 15 years ago

Reputation: 17 865

0

Beam

``P`P''''''''>`++++++)++P'''>`+++++++++++++)''''''''P+++++++++++++`P>`++)'P++++'P++++++'P+++'P+++++'PL>`++++++++)''''''P'''>`++++++)`P'v                                                                         >L```P'''''''''p+@`>`)L++++++++++@@v
>`p'n''''''''p+++++++@````p@````p@''''p--@++@+++@``p-@``>p@'p@'''p@'p@@``p@`p-@```p''n       >`)p@''''p@``p@``p@'p@'p-@@'''p--@>`)``p'' np@''''p@-@````p@'''''p@>`)''p++@---@``p@'''''p+++@>`)'p-@''p@@``````p'''u``+P''''''''p-@`>`)p@``p+P''      v
^   >:                                                  ^                            >''''p-@^                                          >-``P''''''''p+@`>`)`p'nL++++++++++@S``p@````p@````p@'''''p@`p@````p@'''''p@>`)''p++@---@``p@'''''p-@+@`p@++ +@``p-@``p@'p-@'''p-@```p++@`p@'p@''''p+@++++@>`)p@'''''p-@`p@--@``p-@``p@''''p--@p@+++@``p-@''''p-@`>`)p@'p+:`p@'p@'''p@'p@@``p@`p-@'''p-@>`)p@''''p@``p@``p@'p@'p-@@'''p--@>`)p@''''p@-@````p@'''''p@>`)''p++@---@``p@'''''p+++@>`)'p-@''p@@'''p+@H
^                                                                                                                                                              >L++++++++++@S```p@>`)'p-@''p-@`p-@``p@''''p@-@``p-@``p@'p++@'''p@'p+++@`p-@````p@'p- @'''p-@```p++@`p@''''p+@```p-@''''p-@@>`)p@''p+++@'''p@>`)p@'p-@''''p--@`p@'p+@`p-@``p--@''''p-@`>`)p@`p-P`p-P`p+P'''v
^                                                                                                                                      <                                                                                                            <                                                                                                                     <

Try it in the snippet below.

var ITERS_PER_SEC = 100000;
var TIMEOUT_SECS = 50;
var ERROR_INTERRUPT = "Interrupted by user";
var ERROR_TIMEOUT = "Maximum iterations exceeded";
var ERROR_LOSTINSPACE = "Beam is lost in space";

var code, store, beam, ip_x, ip_y, dir, input_ptr, mem;
var input, timeout, width, iterations, running;

function clear_output() {
document.getElementById("output").value = "";
document.getElementById("stderr").innerHTML = "";
}

function stop() {
running = false;
document.getElementById("run").disabled = false;
document.getElementById("stop").disabled = true;
document.getElementById("clear").disabled = false;
document.getElementById("timeout").disabled = false;
}

function interrupt() {
error(ERROR_INTERRUPT);
}

function error(msg) {
document.getElementById("stderr").innerHTML = msg;
stop();
}

function run() {
clear_output();
document.getElementById("run").disabled = true;
document.getElementById("stop").disabled = false;
document.getElementById("clear").disabled = true;
document.getElementById("input").disabled = false;
document.getElementById("timeout").disabled = false;

code = document.getElementById("code").value;
input = document.getElementById("input").value;
timeout = document.getElementById("timeout").checked;
 
code = code.split("\n");
width = 0;
for (var i = 0; i < code.length; ++i){
 if (code[i].length > width){ 
  width = code[i].length;
 }
}
console.log(code);
console.log(width);
 
running = true;
dir = 0;
ip_x = 0;
ip_y = 0;
input_ptr = 0;
beam = 0;
store = 0;
mem = [];
 
input = input.split("").map(function (s) {
  return s.charCodeAt(0);
 });
 
iterations = 0;

beam_iter();
}

function beam_iter() {
while (running) {
 var inst; 
 try {
  inst = code[ip_y][ip_x];
 }
 catch(err) {
  inst = "";
 }
 switch (inst) {
  case ">":
   dir = 0;
   break;
  case "<":
   dir = 1;
   break;
  case "^":
   dir = 2;
   break;
  case "v":
   dir = 3;
   break;
  case "+":
   if(++beam > 255)
    beam = 0;
   break;
  case "-":
   if(--beam < 0)
    beam = 255;
   break;
  case "@":
   document.getElementById("output").value += String.fromCharCode(beam);
   break;
  case ":":
   document.getElementById("output").value += beam;
   break;
  case "/":
   dir ^= 2;
   break;
  case "\\":
   dir ^= 3;
   break;
  case "!":
   if (beam != 0) {
    dir ^= 1;
   }
   break;
  case "?":
   if (beam == 0) {
    dir ^= 1;
   }
   break;
  case "_":
   switch (dir) {
   case 2:
    dir = 3;
    break;
   case 3:
    dir = 2;
    break;
   }
   break;
  case "|":
   switch (dir) {
   case 0:
    dir = 1;
    break;
   case 1:
    dir = 0;
    break;
   }
   break;
  case "H":
   stop();
   break;
  case "S":
   store = beam;
   break;
  case "L":
   beam = store;
   break;
  case "s":
   mem[beam] = store;
   break;
  case "g":
   store = mem[beam];
   break;
  case "P":
   mem[store] = beam;
   break;
  case "p":
   beam = mem[store];
   break;
  case "u":
   if (beam != store) {
    dir = 2;
   }
   break;
  case "n":
   if (beam != store) {
    dir = 3;
   }
   break;
  case "`":
   --store;
   break;
  case "'":
   ++store;
   break;
  case ")":
   if (store != 0) {
    dir = 1;
   }
   break;
  case "(":
   if (store != 0) {
    dir = 0;
   }
   break;
  case "r":
   if (input_ptr >= input.length) {
    beam = 0;
   } else {
    beam = input[input_ptr];
    ++input_ptr;
   }
   break;
  }
 // Move instruction pointer
 switch (dir) {
  case 0:
   ip_x++;
   break;
  case 1:
   ip_x--;
   break;
  case 2:
   ip_y--;
   break;
  case 3:
   ip_y++;
   break;
 }
 if (running && (ip_x < 0 || ip_y < 0 || ip_x >= width || ip_y >= code.length)) {
  error(ERROR_LOSTINSPACE);
 }
 ++iterations;
 if (iterations > ITERS_PER_SEC * TIMEOUT_SECS) {
  error(ERROR_TIMEOUT);
 }
}
}
<div style="font-size:12px;font-family:Verdana, Geneva, sans-serif;">Code:
    <br>
    <textarea id="code" rows="8" style="overflow:scroll;overflow-x:hidden;width:90%;">``P`P''''''''>`++++++)++P'''>`+++++++++++++)''''''''P+++++++++++++`P>`++)'P++++'P++++++'P+++'P+++++'PL>`++++++++)''''''P'''>`++++++)`P'v                                                                         >L```P'''''''''p+@`>`)L++++++++++@@v
>`p'n''''''''p+++++++@````p@````p@''''p--@++@+++@``p-@``>p@'p@'''p@'p@@``p@`p-@```p''n       >`)p@''''p@``p@``p@'p@'p-@@'''p--@>`)``p'' np@''''p@-@````p@'''''p@>`)''p++@---@``p@'''''p+++@>`)'p-@''p@@``````p'''u``+P''''''''p-@`>`)p@``p+P''      v
^   >:                                                  ^                            >''''p-@^                                          >-``P''''''''p+@`>`)`p'nL++++++++++@S``p@````p@````p@'''''p@`p@````p@'''''p@>`)''p++@---@``p@'''''p-@+@`p@++ +@``p-@``p@'p-@'''p-@```p++@`p@'p@''''p+@++++@>`)p@'''''p-@`p@--@``p-@``p@''''p--@p@+++@``p-@''''p-@`>`)p@'p+:`p@'p@'''p@'p@@``p@`p-@'''p-@>`)p@''''p@``p@``p@'p@'p-@@'''p--@>`)p@''''p@-@````p@'''''p@>`)''p++@---@``p@'''''p+++@>`)'p-@''p@@'''p+@H
^                                                                                                                                                              >L++++++++++@S```p@>`)'p-@''p-@`p-@``p@''''p@-@``p-@``p@'p++@'''p@'p+++@`p-@````p@'p- @'''p-@```p++@`p@''''p+@```p-@''''p-@@>`)p@''p+++@'''p@>`)p@'p-@''''p--@`p@'p+@`p-@``p--@''''p-@`>`)p@`p-P`p-P`p+P'''v
^                                                                                                                                      <                                                                                                            <                                                                                                                     <
</textarea>
    <p>Timeout:
        <input id="timeout" type="checkbox" checked="checked">&nbsp;
        <br>
        <br>
        <input id="run" type="button" value="Run" onclick="run()">
        <input id="stop" type="button" value="Stop" onclick="interrupt()" disabled="disabled">
        <input id="clear" type="button" value="Clear" onclick="clear_output()">&nbsp; <span id="stderr" style="color:red"></span>
    </p>Output:
    <br>
    <textarea id="output" rows="6" style="overflow:scroll;width:90%;"></textarea>
    <br>Input:
    <br>
    <textarea id="input" rows="2" style="overflow:scroll;overflow-x:hidden;width:90%;"></textarea>
</div>

MickyT

Posted 15 years ago

Reputation: 11 735

0

Javascript (249 bytes)

Recursive with arrow function.

This suppose that the return of the code is outputted with '\n' kept.

a=(b,w,p,f)=>b?(b+" bottle"+(b-1?"s":"")+" of beer"+(w?" on the wall":"")+(p?".\n":", ")+(f?"":(!w&&p?(--b?"Take one down and pass it around, "+a(b,1,1):"Go to the store and buy some more, "+a(99,1,1,1)):(w&&p?"\n"+a(b,1,0):a(b,0,1))))):"";a(99,1,0)

Naouak

Posted 15 years ago

Reputation: 349

-3

191 Characters. Using PHP:

<? for ($i = 100; $i <= 100; $i--) {$j = $i-1;echo "$i bottles of beer on the wall, $i bottles of beer.<br /> Take one down and pass it around, $j bottles of beer on the wall. <br /><br />";}

C'mon

Posted 15 years ago

Reputation: 75

What's about going to store... – F. Hauri – 12 years ago

2You could've at least mentioned that this goes on forever... – RobIII – 12 years ago