99 Bottles of Beer
From Rosetta Code
X bottles of beer on the wall X bottles of beer Take one down, pass it around X-1 bottles of beer on the wall X-1 bottles of beer on the wall ... Take one down, pass it around 0 bottles of beer on the wall
Where X and X-1 are replaced by numbers of course. Grammatical support for "1 bottle of beer" is optional. As with any puzzle, try to do it in as creative/concise/comical a way as possible (simple, obvious solutions allowed, too).
See also: http://99-bottles-of-beer.net/
[edit] Ada
[edit] Simple version
with Ada.Text_Io; use Ada.Text_Io;
procedure Bottles is
begin
for X in reverse 1..99 loop
Put_Line(Integer'Image(X) & " bottles of beer on the wall");
Put_Line(Integer'Image(X) & " bottles of beer");
Put_Line("Take one down, pass it around");
Put_Line(Integer'Image(X - 1) & " bottles of beer on the wall");
New_Line;
end loop;
end Bottles;
[edit] Concurrent version
with 1 task to print out the information and 99 tasks to specify the number of bottles
with Ada.Text_Io; use Ada.Text_Io;
procedure Tasking_99_Bottles is
subtype Num_Bottles is Natural range 1..99;
task Print is
entry Set (Num_Bottles);
end Print;
task body Print is
Num : Natural;
begin
for I in reverse Num_Bottles'range loop
select
accept
Set(I) do -- Rendezvous with Counter task I
Num := I;
end Set;
Put_Line(Integer'Image(Num) & " bottles of beer on the wall");
Put_Line(Integer'Image(Num) & " bottles of beer");
Put_Line("Take one down, pass it around");
Put_Line(Integer'Image(Num - 1) & " bottles of beer on the wall");
New_Line;
or terminate; -- end when all Counter tasks have completed
end select;
end loop;
end Print;
task type Counter(I : Num_Bottles);
task body Counter is
begin
Print.Set(I);
end Counter;
type Task_Access is access Counter;
Task_List : array(Num_Bottles) of Task_Access;
begin
for I in Task_List'range loop -- Create 99 Counter tasks
Task_List(I) := new Counter(I);
end loop;
end Tasking_99_Bottles;
[edit] ALGOL 68
Works with: ALGOL 68 version Standard - no extensions to language used Works with: ALGOL 68G version Any - tested with release mk15-0.8b.fc9.i386
main:(
FOR bottles FROM 99 TO 1 BY -1 DO
printf(($z-d" bottles of beer on the wall"l$, bottles));
printf(($z-d" bottles of beer"l$, bottles));
printf(($"Take one down, pass it around"l$));
printf(($z-d" bottles of beer on the wall"ll$, bottles-1))
OD
)
[edit] AmigaE
PROC main()
DEF t: PTR TO CHAR,
s: PTR TO CHAR,
u: PTR TO CHAR, i, x
t := 'Take one down, pass it around\n'
s := '\d bottle\s of beer\s\n'
u := ' on the wall'
FOR i := 99 TO 0 STEP -1
ForAll({x}, [u, NIL], `WriteF(s, i, IF i <> 1 THEN 's' ELSE NIL,
x))
IF i > 0 THEN WriteF(t)
ENDFOR
ENDPROC
[edit] APL
Works with: Dyalog APL
Translation of: J
bob ← { (⍕⍵), ' bottle', (1=⍵)↓'s of beer'}
bobw ← {(bob ⍵) , ' on the wall'}
beer ← { (bobw ⍵) , ', ', (bob ⍵) , '; take one down and pass it around, ', bobw ⍵-1}
↑beer¨ ⌽(1-⎕IO)+⍳99
[edit] AutoHotkey
Delayed Sing along
n=99
Gui, Font, s20 cMaroon, Comic Sans MS
Gui, Add, Text, w500 vLyrics, %n% bottles of beer on the wall...
Gui, Show
Loop {
Sleep, 2000
GuiControl,,Lyrics,% n!=1 ? n " bottles of beer.":n " bottle of beer."
Sleep, 2000
GuiControl,,Lyrics,% n ? "Take one down, pass it around...":"Go to the store, buy some more..."
Sleep, 2000
n := n ? --n:99
GuiControl,,Lyrics,% n!=1 ? n " bottles of beer on the wall.":n " bottle of beer on the wall."
Sleep, 2000
GuiControl,,Lyrics,% n!=1 ? n " bottles of beer on the wall...":n " bottle of beer on the wall..."
}
GuiClose:
ExitApp
Fast and Short
b=99
Loop, %b% {
s := b " bottles of beer on the wall, " b "bottles of beer, Take one down, pass it around " b-1 " bottles of beer on the wall"
b--
TrayTip,,%s%
sleep, 40
}
[edit] AWK
{ i = 99
while (i > 0)
{print i, " bottles of beer on the wall,"
print i, " bottles of beer."
print "Take one down, pass it around,"
i--
print i, " bottles of beer on the wall\n"}}
[edit] BASIC
Works with: QuickBasic version 4.5
[edit] Sound
This version plays the tune 100 times while printing out the lyrics (not synchronized).
PLAY "<"
FOR x = 99 TO 0 STEP -1
PRINT x; "bottles of beer on the wall"
PRINT x; "bottles of beer"
PRINT "Take one down, pass it around"
PRINT x-1; "bottles of beer on the wall"
PLAY "e-8e-8e-8<b-8b-8b-8>e-8e-8e-8e-4"'X bottles of beer on the wall
PLAY "f8f8f8c8c8c8f4"'X bottles of beer
PLAY "d4d8d8 N0 d8d8d8d4"'take one down, pass it around
PLAY "<a+8a+8a+8>c8c8d8d+8d+8d+8d+4"'X-1 bottles of beer on the wall
NEXT x
[edit] Text
FOR x = 99 TO 1 STEP -1
PRINT x; "bottles of beer on the wall"
PRINT x; "bottles of beer"
PRINT "Take one down, pass it around"
PRINT x-1; "bottles of beer on the wall"
NEXT x
[edit] C
Translation of: C++
[edit] The simple solution
#include <stdio.h>
int main() {
int bottles = 99;
do {
printf("%d bottles of beer on the wall\n", bottles);
printf("%d bottles of beer\n", bottles);
printf("Take one down, pass it around\n");
printf("%d bottles of beer on the wall\n\n", --bottles);
} while( bottles > 0 );
return 0;
}
[edit] A preprocessor solution
Of course, with the template metaprogramming solution, the program has still do the conversion of numbers to strings at runtime, and those function calls also cost unnecessary time. Couldn't we just compose the complete text at compile time, and just output it at run time? Well, with the preprocessor, that's indeed possible:
#include <stdio.h>
#define BOTTLE(nstr) nstr " bottles of beer"
#define WALL(nstr) BOTTLE(nstr) " on the wall"
#define PART1(nstr) WALL(nstr) "\n" BOTTLE(nstr) \
"\nTake one down, pass it around\n"
#define PART2(nstr) WALL(nstr) "\n\n"
#define MIDDLE(nstr) PART2(nstr) PART1(nstr)
#define SONG PART1("100") CD2 PART2("0")
#define CD2 CD3("9") CD3("8") CD3("7") CD3("6") CD3("5") \
CD3("4") CD3("3") CD3("2") CD3("1") CD4("")
#define CD3(pre) CD4(pre) MIDDLE(pre "0")
#define CD4(pre) MIDDLE(pre "9") MIDDLE(pre "8") MIDDLE(pre "7") \
MIDDLE(pre "6") MIDDLE(pre "5") MIDDLE(pre "4") MIDDLE(pre "3") \
MIDDLE(pre "2") MIDDLE(pre "1")
int main()
{
printf(SONG);
return 0;
}
An inspection of the generated executable proves that it indeed contains the complete text of the song in one block.
[edit] C++
[edit] The simple solution
#include <iostream>
using namespace std;
int main() {
int bottles = 99;
do {
cout << bottles << " bottles of beer on the wall" << endl;
cout << bottles << " bottles of beer" << endl;
cout << "Take one down, pass it around" << endl;
cout << --bottles << " bottles of beer on the wall\n" << endl;
} while (bottles > 0);
}
[edit] An object-oriented solution
See: 99 Bottles of Beer/C++/Object Oriented
[edit] A template metaprogramming solution
Of course, the output of the program always looks the same. One may therefore question why the program has to do all that tedious subtracting during runtime. Couldn't the compiler just generate the code to output the text, with ready-calculated constants? Indeed, it can, and the technique is called template metaprogramming. The following short code gives the text without containing a single variable, let alone a loop:
#include <iostream>
template<int max, int min> struct bottle_countdown
{
static const int middle = (min + max)/2;
static void print()
{
bottle_countdown<max, middle+1>::print();
bottle_countdown<middle, min>::print();
}
};
template<int value> struct bottle_countdown<value, value>
{
static void print()
{
std::cout << value << " bottles of beer on the wall\n"
<< value << " bottles of beer\n"
<< "Take one down, pass it around\n"
<< value-1 << " bottles of beer\n\n";
}
};
int main()
{
bottle_countdown<100, 1>::print();
return 0;
}
[edit] A Recursive solution
#include <iostream>
using namespace std;
void rec(int bottles)
{
if ( bottles!=0)
{
cout << bottles << " bottles of beer on the wall" << endl;
cout << bottles << " bottles of beer" << endl;
cout << "Take one down, pass it around" << endl;
cout << --bottles << " bottles of beer on the wall\n" << endl;
rec(bottles);
}
}
int main()
{
rec(99);
system("pause");
return 0;
}
[edit] A preprocessor solution
Of course, with the template metaprogramming solution, the program has still do the conversion of numbers to strings at runtime, and those function calls also cost unnecessary time. Couldn't we just compose the complete text at compile time, and just output it at run time? Well, with the preprocessor, that's indeed possible:
#include <iostream>
#include <ostream>
#define BOTTLE(nstr) nstr " bottles of beer"
#define WALL(nstr) BOTTLE(nstr) " on the wall"
#define PART1(nstr) WALL(nstr) "\n" BOTTLE(nstr) \
"\nTake one down, pass it around\n"
#define PART2(nstr) WALL(nstr) "\n\n"
#define MIDDLE(nstr) PART2(nstr) PART1(nstr)
#define SONG PART1("100") CD2 PART2("0")
#define CD2 CD3("9") CD3("8") CD3("7") CD3("6") CD3("5") \
CD3("4") CD3("3") CD3("2") CD3("1") CD4("")
#define CD3(pre) CD4(pre) MIDDLE(pre "0")
#define CD4(pre) MIDDLE(pre "9") MIDDLE(pre "8") MIDDLE(pre "7") \
MIDDLE(pre "6") MIDDLE(pre "5") MIDDLE(pre "4") MIDDLE(pre "3") \
MIDDLE(pre "2") MIDDLE(pre "1")
int main()
{
std::cout << SONG;
return 0;
}
[edit] C#
using System;
class Program
{
static void Main(string[] args)
{
for (int i = 99; i > -1; i--)
{
if (i == 0)
{
Console.WriteLine("No more bottles of beer on the wall, no more bottles of beer.");
Console.WriteLine("Go to the store and buy some more, 99 bottles of beer on the wall.");
break;
}
if (i == 1)
{
Console.WriteLine("1 bottle of beer on the wall, 1 bottle of beer.");
Console.WriteLine("Take one down and pass it around, no more bottles of beer on the wall.");
Console.WriteLine();
}
else
{
Console.WriteLine("{0} bottles of beer on the wall, {0} bottles of beer.", i);
Console.WriteLine("Take one down and pass it around, {0} bottles of beer on the wall.", i - 1);
Console.WriteLine();
}
}
}
}
[edit] Another Implementation using Linq
class Program
{
static void Main(string[] args)
{
var query =from total in Enumerable.Range(0,100).Reverse()
select new {
Word=(total>0
? string.Format("{0} bottles of beer on the wall\n{0} bottles of beer\nTake one down, pass it around", total)
:string.Format("{0} bottles left",total))};
foreach (var item in query)
{
Console.WriteLine(item.Word);
}
Console.ReadLine();
}
}
[edit] Clojure
(defn verse [n]
(printf
"%d bottles of beer on the wall
%d bottles of beer
Take one down, pass it around
%d bottles of beer on the wall\n\n" n n (dec n)))
(defn sing [start]
(dorun (map verse (range start 0 -1))))
[edit] Common Lisp
(defun bottles (x)
(loop for bottles from x downto 1
do (format t "~a bottle~:p of beer on the wall
~:*~a bottle~:p of beer
Take one down, pass it around
~a bottle~:p of beer on the wall~2%" bottles (1- bottles))))
and then just call
(bottles 99)
[edit] D
Uses a non-commutative operator to construct a narrative expression of 99-bottles song.
module nbottles ;
import std.string ;
import std.stdio ;
alias Exception NoMoreBottlesLeft ;
enum { // role
None = 0x0, // normal for OP and Term
Taker = 0x1, // for OP that minus one bottlesLeft
Viewer = 0x2, // for Term display bottlesLeft
NewLine = 0x4, // for Term that sending a newline to IO
}
class XP {
static string[] ones = ["","one","two","three","four",
"five","six","seven","eight","nine"] ;
static string[] tens = ["", "ten", "twenty","thirty","fourty",
"fifty","sixty","seventy","eighty","ninty"] ;
static string[] teens = ["","eleven","twelve","thirteen","fourteen",
"fifteen","sixteen","seventeen","eighteen","nineteen"] ;
static private int bottlesLeft = 99 ;
static bool opCall() {
if (bottlesLeft == 0)
throw new NoMoreBottlesLeft("") ;
return true ;
}
static string Cap(string s) {
return toupper(s[0..1]) ~ s[1..$] ;
}
static string num2word(int i) {
if (i == 0)
return "No more" ;
//return std.string.toString(i) ;
string[2] digits ;
int numTen = i / 10 ;
int numOne = i % 10 ;
if(i == 10)
digits[1] = tens[1] ;
else if(numTen == 0)
digits[1] = ones[numOne] ;
else if(numTen == 1)
digits[1] = teens[numOne] ;
else {
digits[0] = tens[numTen] ;
digits[1] = ones[numOne] ;
}
return Cap(strip(join(digits," "))) ;
}
static string getBottles() {
string num = num2word(bottlesLeft) ;
string pural = (bottlesLeft != 1) ? "s" : "";
return num ~ " bottle" ~ pural ;
}
string words ;
int role ;
this (string w, int r) { words = w, role = r ; }
string getWord() {
string postfix = " ";
string word ;
if (words is null)
return "" ;
else
word = words ;
if (role & Viewer)
word = getBottles ;
if (role & NewLine)
postfix = "\n" ;
return word ~ postfix ;
}
}
alias XP A_drunker_sings_a_song ;
class Term : XP {
this (string w = null, int r = None) { super(w, r) ; }
}
class OP : XP {
this (string w = null, int r = None) { super(w, r) ; }
OP opDiv_r(Term t) {
if(role & Taker)
A_drunker_sings_a_song.bottlesLeft-- ;
writef(t.getWord) ;
writef(getWord) ;
return this ;
}
Term opDiv(Term t) {
writef(t.getWord) ;
return new Term ;
}
}
void main() {
Term N_bottles = new Term("", Viewer) ;
OP of = new OP("of") ;
Term beer = new Term("beer") ;
OP on = new OP("on") ;
Term the_wall = new Term("the wall", NewLine) ;
Term beer_ = new Term("beer", NewLine) ;
Term Take = new Term("Take") ;
OP one = new OP("one", Taker) ;
Term down = new Term("down,") ;
Term pass = new Term("pass") ;
OP it = new OP("it") ;
Term around = new Term("around", NewLine) ;
Term the_wall_ = new Term("the wall\n", NewLine) ;
try{
for(; A_drunker_sings_a_song();
N_bottles/of/beer/on/the_wall,
N_bottles/of/beer_ ,
Take/one/down, pass/it/around,
N_bottles/of/beer/on/the_wall_
) {}
} catch (NoMoreBottlesLeft e) {
writefln("Go buy more beer!") ;
}
}
[edit] E
def bottles(n) {
return switch (n) {
match ==0 { "No bottles" }
match ==1 { "1 bottle" }
match _ { `$n bottles` }
}
}
for n in (1..99).descending() {
println(`${bottles(n)} of beer on the wall,
${bottles(n)} of beer.
Take one down, pass it around,
${bottles(n.previous())} of beer on the wall.
`)
}
[edit] Erlang
-module(beersong).
-export([sing/0]).
-define(TEMPLATE_0, "~s of beer on the wall, ~s of beer.~nGo to the store and buy some more, 99
bottles of beer on the wall.~n").
-define(TEMPLATE_N, "~s of beer on the wall, ~s of beer.~nTake one down and pass it around, ~s of
beer on the wall.~n~n").
create_verse(0) -> {0, io_lib:format(?TEMPLATE_0, phrase(0))};
create_verse(Bottle) -> {Bottle, io_lib:format(?TEMPLATE_N, phrase(Bottle))}.
phrase(0) -> ["No more bottles", "no more bottles"];
phrase(1) -> ["1 bottle", "1 bottle", "no more bottles"];
phrase(2) -> ["2 bottles", "2 bottles", "1 bottle"];
phrase(Bottle) -> lists:duplicate(2, integer_to_list(Bottle) ++ " bottles") ++
[integer_to_list(Bottle-1) ++ " bottles"].
bottles() -> lists:reverse(lists:seq(0,99)).
sing() ->
lists:foreach(fun spawn_singer/1, bottles()),
sing_verse(99).
spawn_singer(Bottle) ->
Pid = self(),
spawn(fun() -> Pid ! create_verse(Bottle) end).
sing_verse(Bottle) ->
receive
{_, Verse} when Bottle == 0 ->
io:format(Verse);
{N, Verse} when Bottle == N ->
io:format(Verse),
sing_verse(Bottle-1)
after
3000 ->
io:format("Verse not received - re-starting singer~n"),
spawn_singer(Bottle),
sing_verse(Bottle)
end.
[edit] Factor
USING: io kernel make math math.parser math.ranges sequences ;
: bottle ( -- quot )
[
[
[
[ # " bottles of beer on the wall,\n" % ]
[ # " bottles of beer.\n" % ] bi
] keep
"Take one down, pass it around,\n" %
1 - # " bottles of beer on the wall\n" %
] " " make print
] ; inline
: last-verse ( -- )
"Go to the store and buy some more,"
"no more bottles of beer on the wall!" [ print ] bi@ ;
: bottles ( n -- )
1 [a,b] bottle each last-verse ;
! Usage: 99 bottles
[edit] Falcon
for i in [99:1]
> i, " bottles of beer on the wall"
> i, " bottles of beer"
> "Take one down, pass it around"
> i-1, " bottles of beer on the wall\n"
end
A more robust version to handle plural/not plural conditions
for i in [99:1]
plural = (i != 1) ? 's' : ""
> @ "$i bottle$plural of beer on the wall"
> @ "$i bottle$plural of beer"
> "Take one down, pass it around"
> i-1, @ " bottle$plural of beer on the wall\n"
end
[edit] FALSE
[$." bottle"$1-["s"]?" of beer"]b:
99
[$][b;!" on the wall
"b;!"
Take one down and pass it around
"1-b;!" on the wall
"]#%
[edit] Forth
:noname dup . ." bottles" ;
:noname ." 1 bottle" ;
:noname ." no more bottles" ;
create bottles , , ,
: .bottles dup 2 min cells bottles + @ execute ;
: .beer .bottles ." of beer" ;
: .wall .beer ." on the wall" ;
: .take ." Take one down, pass it around" ;
: .verse .wall cr .beer cr
1- .take cr .wall cr ;
: verses begin cr .verse ?dup 0= until ;
99 verses
[edit] Fortran
program bottlestest
implicit none
integer :: i
character(len=*), parameter :: bwall = " on the wall", &
bottles = "bottles of beer", &
bottle = "bottle of beer", &
take = "Take one down, pass it around", &
form = "(I0, ' ', A)"
do i = 99,0,-1
if ( i /= 1 ) then
write (*,form) i, bottles // bwall
if ( i > 0 ) write (*,form) i, bottles
else
write (*,form) i, bottle // bwall
write (*,form) i, bottle
end if
if ( i > 0 ) write (*,*) take
end do
end program bottlestest
[edit] F#
#light
let rec bottles n =
let (before, after) = match n with
| 1 -> ("bottle", "bottles")
| 2 -> ("bottles", "bottle")
| n -> ("bottles", "bottles")
printfn "%d %s of beer on the wall" n before
printfn "%d %s of beer" n before
printfn "Take one down, pass it around"
printfn "%d %s of beer on the wall\n" (n - 1) after
if n > 1 then
bottles (n - 1)
[edit] Groovy
[edit] Basic Solution
With a closure to handle special cardinalities of bottles.
def bottles = { "${it==0 ? 'No more' : it} bottle${it==1 ? '' : 's' }" }
99.downto(1) { i ->
print """
${bottles(i)} of beer on the wall
${bottles(i)} of beer
Take one down, pass it around
${bottles(i-1)} of beer on the wall
"""
}
[edit] Bottomless Beer Solution
Using more closures to create a richer lyrical experience.
def bottles = { "${it==0 ? 'No more' : it} bottle${it==1 ? '' : 's' }" }
def initialState = {
"""${result(it)}
${resultShort(it)}"""
}
def act = {
it > 0 ?
"Take ${it==1 ? 'it' : 'one'} down, pass it around" :
"Go to the store, buy some more"
}
def delta = { it > 0 ? -1 : 99 }
def resultShort = { "${bottles(it)} of beer" }
def result = { "${resultShort(it)} on the wall" }
// //// uncomment commented lines to create endless drunken binge //// //
// while (true) {
99.downto(0) { i ->
print """
${initialState(i)}
${act(i)}
${result(i+delta(i))}
"""
}
// Thread.sleep(1000)
// }
[edit] gnuplot
if (!exists("bottles")) bottles = 99
print sprintf("%i bottles of beer on the wall", bottles)
print sprintf("%i bottles of beer", bottles)
print "Take one down, pass it around"
bottles = bottles - 1
print sprintf("%i bottles of beer on the wall", bottles)
print ""
if (bottles > 0) reread
[edit] Haskell
A relatively concise solution:
main = mapM_ (putStrLn . beer) [99, 98 .. 0]
beer 1 = "1 bottle of beer on the wall\n1 bottle of beer\nTake one down, pass it around"
beer 0 = "better go to the store and buy some more."
beer v = show v ++ " bottles of beer on the wall\n"
++ show v
++" bottles of beer\nTake one down, pass it around\n"
++ head (lines $ beer $ v-1) ++ "\n"
As a list comprehension:
import qualified Char
main = putStr $ concat
[up (bob n) ++ wall ++ ", " ++ bob n ++ ".\n" ++
pass n ++ bob (n - 1) ++ wall ++ ".\n\n" |
n <- [99, 98 .. 0]]
where bob n = (num n) ++ " bottle" ++ (s n) ++ " of beer"
wall = " on the wall"
pass 0 = "Go to the store and buy some more, "
pass _ = "Take one down and pass it around, "
up (x : xs) = Char.toUpper x : xs
num (-1) = "99"
num 0 = "no more"
num n = show n
s 1 = ""
s _ = "s"
Another version, which uses a Writer monad to collect each part of the song. It also uses Template Haskell to generate the song at compile time.
{-# LANGUAGE TemplateHaskell #-}
-- build with "ghc --make beer.hs"
module Main where
import Language.Haskell.TH
import Control.Monad.Writer
-- This is calculated at compile time, and is equivalent to
-- songString = "99 bottles of beer on the wall\n99 bottles..."
songString =
$(let
sing = tell -- we can't sing very well...
someBottles 1 = "1 bottle of beer "
someBottles n = show n ++ " bottles of beer "
bottlesOfBeer n = (someBottles n ++)
verse n = do
sing $ n `bottlesOfBeer` "on the wall\n"
sing $ n `bottlesOfBeer` "\n"
sing $ "Take one down, pass it around\n"
sing $ (n - 1) `bottlesOfBeer` "on the wall\n\n"
song = execWriter $ mapM_ verse [99,98..1]
in return $ LitE $ StringL $ song)
main = putStr songString
[edit] haXe
class RosettaDemo
{
static public function main()
{
singBottlesOfBeer(100);
}
static function singBottlesOfBeer(bottles : Int)
{
var plural : String = 's';
while (bottles >= 1)
{
neko.Lib.print(bottles + " bottle" + plural + " of beer on the wall,\n");
neko.Lib.print(bottles + " bottle" + plural + " of beer!\n");
neko.Lib.print("Take one down, pass it around,\n");
if (bottles - 1 == 1)
{
plural = '';
}
if (bottles > 1)
{
neko.Lib.print(bottles-1 + " bottle" + plural + " of beer on the wall!\n\n");
}
else
{
neko.Lib.print("No more bottles of beer on the wall!\n");
}
bottles--;
}
}
}
[edit] HQ9+
9
[edit] Io
bottles := method(i,
if(i==0, return "no more bottles of beer")
if(i==1, return "1 bottle of beer")
"" .. i .. " bottles of beer"
)
for(i, 99, 1, -1,
write(
bottles(i), " on the wall, ",
bottles(i), ",\n",
"take one down, pass it around,\n",
bottles(i - 1), " on the wall.\n\n"
)
)
[edit] J
As posted at the J wiki
bob =: ": , ' bottle' , (1 = ]) }. 's of beer'"_
bobw=: bob , ' on the wall'"_
beer=: bobw , ', ' , bob , '; take one down and pass it around, ' , bobw@<:
beer"0 >:i.-99
[edit] Java
[edit] Console
MessageFormat's choice operator is used to properly format plurals.
import java.text.MessageFormat;
public class Beer{
static String bottles(int n){
return MessageFormat.format("{0,choice,0#No more bottles|1#One bottle|2#{0} bottles} of beer", n);
}
public static void main(String[] args){
String byob = bottles(99);
for (int x = 99; x > 0;) {
System.out.println(byob + " on the wall");
System.out.println(byob);
System.out.println("Take one down, pass it around");
byob = bottles(--x);
System.out.println(byob + " on the wall\n");
}
}
}
[edit] An object-oriented solution
Translation of: C++
See: 99 Bottles of Beer/Java/Object Oriented
[edit] GUI
Library: Swing Library: AWT This version requires user interaction. The first two lines are shown in a text area on a window. The third line is shown on a button which you need to click to see the fourth line in a message box. The numbers update and the process repeats until "0 bottles of beer on the wall" is shown in a message box, when the program ends.
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
public class Beer extends JFrame implements ActionListener{
private int x;
private JButton take;
private JTextArea text;
public static void main(String[] args){
new Beer();//build and show the GUI
}
public Beer(){
x= 99;
take= new JButton("Take one down, pass it around");
text= new JTextArea(4,30);//size the area to 4 lines, 30 chars each
text.setText(x + " bottles of beer on the wall\n" + x + " bottles of beer");
text.setEditable(false);//so they can't change the text after it's displayed
take.addActionListener(this);//listen to the button
setLayout(new BorderLayout());//handle placement of components
add(text, BorderLayout.CENTER);//put the text area in the largest section
add(take, BorderLayout.SOUTH);//put the button underneath it
pack();//auto-size the window
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//exit on "X" (I hate System.exit...)
setVisible(true);//show it
}
public void actionPerformed(ActionEvent arg0){
if(arg0.getSource() == take){//if they clicked the button
JOptionPane.showMessageDialog(null, --x + " bottles of beer on the wall");//show a popup message
text.setText(x + " bottles of beer on the wall\n" + x + " bottles of beer");//change the text
}
if(x == 0){//if it's the end
dispose();//end
}
}
}
[edit] IDL
Pro bottles
for i=1,99 do begin
print, 100-i, " bottles of beer on the wall.", 100-i, $
" bottles of beer.", " Take one down, pass it around," , $
99-i, " bottles of beer on the wall."
endfor
End
}
[edit] JavaScript
// Line breaks are in HTML
var beer = 99;
while ( beer > 0)
{
document.write( beer + " bottles of beer on the wall<br>" );
document.write( beer + " bottles of beer<br>" );
document.write( "Take one down, pass it around<br>" );
document.write( ( beer - 1 ) + " bottles of beer on the wall<br>" );
beer--;
}
[edit] Joy
LIBRA
_beerlib == true ;
HIDE
beer == "of beer " putchars ;
wall == "on the wall" putchars ;
take1 == "Take one down and pass it around, " putchars ;
dup3 == dup dup dup ;
comma == ", " putchars ;
period == '. putch ;
bottles == [dup small]
[ [null] [pop "no more bottles " putchars] [put "bottle " putchars] ifte]
[put "bottles " putchars] ifte ;
sing-verse == dup3 bottles beer wall comma
bottles beer ".\n" putchars
take1 1 - bottles beer wall period newline newline ;
sing-verse-0 == "No more bottles of beer on the wall, no more bottles of beer\n" putchars
"Go to the store and buy some more, " putchars
99 bottles pop beer wall period newline ;
IN
(* n -- *)
sing-verses == [null]
[sing-verse-0]
[sing-verse 1 -] tailrec .
[edit] LaTeX
[edit] Recursive
\documentclass{article}
\newcounter{beer}
\newcommand{\verses}[1]{
\setcounter{beer}{#1}
\par\noindent
\arabic{beer} bottles of beer on the wall,\\
\arabic{beer} bottles of beer!\\
Take one down, pass it around---\\
\addtocounter{beer}{-1}
\arabic{beer} bottles of beer on the wall!\\
\ifnum#1>0
\verses{\value{beer}}
\fi
}
\begin{document}
\verses{99}
\end{document}
[edit] Iterative
The \loop macro is tail-recursive (Knuth 1984, page 219). Just for fun, this version uses Roman numerals.
\documentclass{article}
\newcounter{beer}
\newcounter{showC}
\newcommand{\verses}[1]{
\setcounter{beer}{#1}
\loop
\par\noindent
\Roman{beer} bottles of beer on the wall,\\
\Roman{beer} bottles of beer!\\
Take one down, pass it around---\\
\addtocounter{beer}{-1}
% Romans didn't know how to write zero ;-)
\ifnum\value{beer}=0 ZERO \else\Roman{beer} \fi
bottles of beer on the wall!\\
\ifnum\value{beer}>0
\repeat
}
\begin{document}
\verses{99}
\end{document}
[edit] References
- Knuth, Donald E. (1984). The TeXbook, Addison Wesley.
[edit] Logo
to bottles :n
if :n = 0 [output [No more bottles]]
if :n = 1 [output [1 bottle]]
output sentence :n "bottles
end
to verse :n
print sentence bottles :n [of beer on the wall]
print sentence bottles :n [of beer]
print [Take one down, pass it around]
print sentence bottles :n-1 [of beer on the wall]
end
for [n 99 1] [verse :n (print)]
[edit] Lua
local bottles = 99
local function plural (bottles) if bottles == 1 then return '' end return 's' end
while bottles > 0 do
print (bottles..' bottle'..plural(bottles)..' of beer on the wall')
print (bottles..' bottle'..plural(bottles)..' of beer')
print ('Take one down, pass it around')
bottles = bottles - 1
print (bottles..' bottle'..plural(bottles)..' of beer on the wall')
print ()
end
[edit] Lucid
// Run luval with -s inside the lucid shell script
// The print out is a list of lines. So the output is not separated by new lines, rather
// by '[' and ']' -- I cant figure out how to do string concatenation with numbers in lucid.
// beer(N) ^ bottle(N) ^ wall ^ beer(N) ^ bottle(N) ^ pass ^ beer(N-1) ^ bottle(N-1) ^ wall
// should have worked but doesn't
[%beer(N),bottle(N),wall,beer(N),bottle(N),pass,beer(N-1),bottle(N-1),wall%]
where
N = 100 fby N - 1;
wall = if N > 0 then ` On the wall ' else eod fi;
pass = `Take one down and pass it around.';
beer(A) = if A > 0 then A else `No more' fi;
bottle(A) = if A eq 1 then `bottle of beer' else `bottles of beer' fi;
end
[edit] M4
define(`BOTTLES', `bottles of beer')dnl
define(`BOTTLE', `bottle of beer')dnl
define(`WALL', `on the wall')dnl
define(`TAKE', `take one down, pass it around')dnl
define(`NINETEEN', `$1 ifelse(`$1',`1',BOTTLE,BOTTLES) WALL
$1 ifelse(`$1',`1',BOTTLE,BOTTLES)
ifelse(`$1',`0',,`TAKE')
ifelse(`$1',`0',,`NINETEEN(eval($1-1))')')dnl
NINETEEN(99)
[edit] Mathematica
texts = ToString[#] <> " bottles of beer on the wall\n" <> ToString[#] <>
" bottles of beer\nTake one down and pass it around\n" <>
ToString[# - 1] <> " bottles of beer on the wall" & /@ Range[99, 1, -1];
AppendTo[texts, "No more bottles of beer on the wall, no more bottles of beer\nGo \
to the store and buy some more, 99 bottles of beer on the wall"];
texts = StringJoin@Riffle[texts, "\n\n"];
Print@StringReplace[texts, "\n1 bottles" -> "\n1 bottle"]
[edit] MAXScript
resetMaxFile #noPrompt
viewport.setType #view_top
max tool maximize
viewport.SetRenderLevel #smoothhighlights
delay = 1.6
a = text size:30
a.wirecolor = white
theMod = extrude()
addModifier a theMod
for i in 99 to 1 by -1 do
(
a.text = (i as string + " bottles of beer on the wall")
redrawViews()
sleep delay
a.text = (i as string + " bottles of beer")
redrawViews()
sleep delay
a.text = "Take one down, pass it around"
redrawViews()
sleep delay
a.text = ((i-1) as string + " bottles of beer on the wall")
redrawViews()
sleep delay
)
[edit] A one-line version
Since MAXscript is an expression based language (everything returns a value), it is relatively easy to write long expressions that are only one line long. the following single-line snippet (broken for clarity on the webpage) produces a grammatically correct printout of the song.
for i = 99 to 1 by -1 do (print (i as string + (if i == 1 then " bottle" else " bottles") + " of beer on the wall\n" + i as string +\
(if i == 1 then " bottle" else " bottles") + " of beer\nTake one down, pass it around\n" + (i - 1) as string + (if i - 1 == 1 then "\
bottle" else " bottles") + " of beer on the wall\n" + (if i - 1 == 0 then "\nno more beer" else "")))
[edit] Make
PRED=`expr $* - 1`
1-bottles: 1-beer pass
@echo "No more bottles of beer on the wall"
%-bottles: %-beer pass
@echo "$(PRED) bottles of beer on the wall\n"
@-make $(PRED)-bottles
1-beer:
@echo "One bottle of beer on the wall, One bottle of beer"
%-beer:
@echo "$* bottles of beer on the wall, $* bottles of beer"
pass:
@echo "Take one down and pass it around,"
Usage
make 99-bottles
[edit] Modula-3
MODULE Bottles EXPORTS Main;
IMPORT IO, Fmt;
BEGIN
FOR i := 99 TO 1 BY -1 DO
IO.Put(Fmt.Int(i) & " bottles of beer on the wall\n");
IO.Put(Fmt.Int(i) & " bottles of beer\n");
IO.Put("Take one down, pass it around\n");
IO.Put(Fmt.Int(i - 1) & " bottles of beer on the wall\n");
IO.Put("\n");
END;
END Bottles.
[edit] MPIF90
program bottlesMPI
implicit none
integer :: ierr,rank,nproc
character(len=*), parameter :: bwall = " on the wall", &
bottles = "bottles of beer", &
bottle = "bottle of beer", &
take = "Take one down, pass it around", &
form = "(I0, ' ', A)"
call mpi_init(ierr)
call mpi_comm_size(MPI_COMM_WORLD,nproc, ierr)
call mpi_comm_rank(MPI_COMM_WORLD,rank,ierr)
if ( rank /= 1 ) then
write (*,form) rank, bottles // bwall
if ( rank > 0 ) write (*,form) rank, bottles
else
write (*,form) rank, bottle // bwall
write (*,form) rank, bottle
end if
if ( rank > 0 ) write (*,*) take
call mpi_finalize(ierr)
end program bottlesMPI
Usage
mpif90 filename.f90 mpiexec -np 99 a.out
[edit] Nial
line is fork [
0=, 'No more bottles of beer' first,
1=, 'One bottle of beer' first,
link [string,' bottles of beer' first]
]
verse is link [
line, ' on the wall, ' first,line,
'. Take it down and pass it around, ' first,
line (-1+),'on the wall. ' first
]
bottles is iterate (write verse) reverse count
[edit] Nimrod
proc GetBottleNumber(n: int): string =
var bs: string
if n == 0:
bs = "No more bottles"
elif n == 1:
bs = "1 bottle"
else:
bs = $n & " bottles"
return bs & " of beer"
for bn in countdown(99, 1):
var cur = GetBottleNumber(bn)
echo(cur, " on the wall, ", cur, ".")
echo("Take one down and pass it around, ", GetBottleNumber(bn-1), " on the wall.\n")
echo "No more bottles of beer on the wall, no more bottles of beer."
echo "Go to the store and buy some more, 99 bottles of beer on the wall."
[edit] OCaml
for n = 99 downto 1 do
Printf.printf "%d bottles of beer on the wall\n" n;
Printf.printf "%d bottles of beer\n" n;
Printf.printf "Take one down, pass it around\n";
Printf.printf "%d bottles of beer on the wall\n\n" (pred n);
done
[edit] Octave
function bottles(n)
bottle = "bottle";
ofbeer = "of beer";
wall = "on the wall";
for i = n:-1:0
if ( i == 1 )
s = "";
else
s = "s";
endif
for j = 0:1
w = wall;
if ( j == 1 )
w = "";
endif
printf("%d %s%s %s %s\n",\
i, bottle, s, ofbeer, w);
endfor
printf("Take one down, pass it around\n");
endfor
endfunction
bottles(99);
[edit] OpenEdge/Progress
DEFINE VARIABLE amountofbottles AS INTEGER NO-UNDO INITIAL 99.
&GLOBAL-DEFINE bbm bottles of beer
&GLOBAL-DEFINE bbs bottle of beer
&GLOBAL-DEFINE otw on the wall
&GLOBAL-DEFINE tow Take one down and pass it around,
&GLOBAL-DEFINE gts Go to the store and buy some more,
FUNCTION drinkBottle RETURNS INTEGER PRIVATE (INPUT bc AS INTEGER) FORWARD.
OUTPUT TO OUTPUT.txt.
drinkBottle(amountofbottles).
OUTPUT CLOSE.
FUNCTION drinkBottle RETURNS INTEGER.
IF bc >= 0 THEN DO:
CASE bc:
WHEN 2 THEN
PUT UNFORMATTED bc " {&bbm} {&otw}, " bc " {&bbm}" SKIP
"{&tow} " bc - 1 " {&bbs} {&otw}" SKIP.
WHEN 1 THEN
PUT UNFORMATTED bc " {&bbs} {&otw}, " bc " {&bbs}" SKIP
"{&tow} no more {&bbm} {&otw}" SKIP.
WHEN 0 THEN
PUT UNFORMATTED "no more" " {&bbm} {&otw}, no more {&bbm}" SKIP
"{>s} " amountofbottles " {&bbm} {&otw}" SKIP.
OTHERWISE
PUT UNFORMATTED bc " {&bbm} {&otw}, " bc " {&bbm}" SKIP
"{&tow} " bc - 1 " {&bbm} {&otw}" SKIP.
END CASE.
drinkBottle(bc - 1).
RETURN bc.
END.
RETURN 0.
END FUNCTION.
[edit] Oz
[edit] Constraint Programming
Note: In real life, you would never solve a simple iterative task like this with constraint programming. This is just for fun.
declare
%% describe the possible solutions of the beer 'puzzle'
proc {BeerDescription Solution}
N = {FD.int 1#99} %% N is an integer in [1, 99]
in
%% distribute starting with highest value
{FD.distribute generic(value:max) [N]}
Solution =
{Bottles N}#" of beer on the wall\n"#
{Bottles N}#" bottles of beer\n"#
"Take one down, pass it around\n"#
{Bottles N-1}#" of beer on the wall\n"
end
%% pluralization
proc {Bottles N Txt}
cond N = 1 then Txt ="1 bottle"
else Txt = N#" bottles"
end
end
in
%% show all solutions to the 'puzzle'
{ForAll {SearchAll BeerDescription}
System.showInfo}
[edit] Iterative
declare
fun {Bottles N}
if N == 1 then "1 bottle"
else N#" bottles"
end
end
in
for I in 99..1;~1 do
{System.showInfo
{Bottles I}#" of beer on the wall\n"#
{Bottles I}#" bottles of beer\n"#
"Take one down, pass it around\n"#
{Bottles I-1}#" of beer on the wall\n"}
end
[edit] Pascal
procedure BottlesOfBeer;
var
i: Integer;
begin
for i := 99 downto 1 do
begin
if i = 1 then
begin
WriteLn('1 bottle of beer on the wall');
WriteLn('1 bottle of beer');
WriteLn('Take one down, pass it around');
WriteLn('No more bottles of beer on the wall');
Exit;
end;
WriteLn(Format('%d bottles of beer on the wall', [i]));
WriteLn(Format('%d bottles of beer', [i]));
WriteLn('Take one down, pass it around');
WriteLn(Format('%d bottles of beer on the wall', [Pred(i)]));
WriteLn('');
end;
end;
[edit] Perl
#!/usr/bin/perl -w
my $verse = <<"VERSE";
100 bottles of beer on the wall,
100 bottles of beer!
Take one down, pass it around!
99 bottles of beer on the wall!
VERSE
foreach (1..99) {
$verse =~ s/(\d+)/$1-1/ge;
$verse =~ s/\b1 bottles/1 bottle/g;
$verse =~ s/\b0 bottle/No bottles/g;
print $verse;
}
[edit] Perl 6
Works with: Rakudo version #22 "Thousand Oaks"
my @quantities = (99 ... 1), 'No more', 99;
my @bottles = 'bottles' xx 98, 'bottle', 'bottles' xx 2;
my @actions = 'Take one down, pass it around' xx 99,
'Go to the store, buy some more';
for @quantities Z @bottles Z @actions Z
@quantities[1 .. *] Z @bottles[1 .. *]
-> $a, $b, $c, $d, $e {
say "$a $b of beer on the wall";
say "$a $b of beer";
say $c;
say "$d $e of beer on the wall\n";
}
[edit] PHP
<?php
$plural = 's';
foreach (range(99, 1) as $i) {
echo "$i bottle$plural of beer on the wall,\n";
echo "$i bottle$plural of beer!\n";
echo "Take one down, pass it around!\n";
if ($i - 1 == 1)
$plural = '';
if ($i > 1)
echo ($i - 1) . " bottle$plural of beer on the wall!\n\n";
else
echo "No more bottles of beer on the wall!\n";
}
?>
Alternatively:
<?php
$verse = <<<VERSE
100 bottles of beer on the wall,
100 bottles of beer!
Take one down, pass it around!
99 bottles of beer on the wall!
VERSE;
foreach (range(1,99) as $i) { // loop 99 times
$verse = preg_replace('/\d+/e', '$0 - 1', $verse);
$verse = preg_replace('/\b1 bottles/', '1 bottle', $verse);
$verse = preg_replace('/\b0 bottle/', 'No bottles', $verse);
echo $verse;
}
?>
[edit] Pike
int main(){
for(int i = 99; i > 0; i--){
write(i + " bottles of beer on the wall, " + i + " bottles of beer.\n");
write("Take one down and pass it around, " + (i-1) + " bottles of beer on the wall.\n\n");
}
write("No more bottles of beer on the wall, no more bottles of beer.\n");
write("Go to the store and buy some more, 99 bottles of beer on the wall.\n");
}
[edit] PlainTeX
\obeylines
\newtoks\bottle \bottle={bottle}
\newtoks\ofbeer \ofbeer={of beer}
\newtoks\onthewall \onthewall={on the wall}
\newtoks\passit \passit={Take one down, pass it around}
\def\song#1{#1 \the\bottle\ifnum#1>1\relax s\fi%
\ \the\ofbeer\ \the\onthewall
#1 \the\bottle\ifnum#1>1\relax s\fi\ \the\ofbeer
\the\passit}
\newcount\bottles \bottles99
\loop\song{\number\bottles}
\advance\bottles-1\ifnum\bottles>1\repeat
0 \the\bottle s \the\ofbeer\ \the\onthewall
\bye
[edit] Pop11
define bootles(n);
while n > 0 do
printf(n, '%p bottles of beer on the wall\n');
printf(n, '%p bottles of beer\n');
printf('Take one down, pass it around\n');
n - 1 -> n;
printf(n, '%p bottles of beer on the wall\n');
endwhile;
enddefine;
bootles(99);
[edit] Prolog
Works with: SWI Prolog
bottles(0):-!.
bottles(X):-
writef('%t bottles of beer on the wall \n',[X]),
writef('%t bottles of beer\n',[X]),
write('Take one down, pass it around\n'),
succ(XN,X),
writef('%t bottles of beer on the wall \n\n',[XN]),
bottles(XN).
:- bottles(99).
[edit] Python
a, b, c, s = " bottles of beer", " on the wall\n", "Take one down, pass it around\n", str
for i in [s(x)+a+b+s(x)+a+"\n"+c+s(x-1)+a+b for x in xrange(99, 0, -1)]: print i
Allowing for correct grammar
def d(n): return (str(n) if n>0 else 'No more')+' bottle'+('s' if n!=1 else '')+' of beer'
b,c = ' on the wall\n','Take one down, pass it around\n'
for x in range(99,0,-1): print d(x)+b+d(x)+'\n'+c+d(x-1)+b
And for a wordy version
l1=('','-one','-two','-three','-four','-five','-six','-seven','-eight','-nine')
m2=('thir','four','fif','six','seven','eigh','nine')
l2= ('','','twenty')+tuple('%sty'%j.replace('u','') for j in m2)
l3=('ten','eleven','twelve')+tuple('%steen'%j for j in m2)
def v(n): t,o=divmod(n,10); return l2[t]+(l1 if t-1 else l3)[o][0 if t else 1:]
def d(n): return (v(n).capitalize()if n>0 else 'No more')+' bottle'+('s' if n!=1 else '')+' of beer'
b,c = ' on the wall\n','Take one down, pass it around\n'
for x in range(99,0,-1): print d(x)+b+d(x)+'\n'+c+d(x-1)+b
Normal Code
for i in range(99,0,-1): #or range(1,100)[::-1]
print "%d bottles of beer on the wall" % i
print "%d bottles of beer" % i
print "Take one down, pass it around"
print "%d bottles of beer on the wall" % (i-1)
[edit] R
bottleofbeer <- function(n) {
v <- 1
for (b in n:0) {
cat(b, " bottle",
ifelse(b!=1, "s", ""),
" of beer on the wall\n",
b, " bottle", ifelse(b!=1, "s", ""), " of beer\n",
"Take one down, pass it around\n", sep="")
}
}
bottleofbeer(99)
[edit] REBOL
rebol [
Title: "99 Bottles of Beer"
Author: oofoe
Date: 2009-12-11
URL: http://rosettacode.org/wiki/99_Bottles_of_Beer
]
; The 'bottles' function maintains correct grammar.
bottles: func [n /local b][
b: either 1 = n ["bottle"]["bottles"]
if 0 = n [n: "no"]
reform [n b]
]
for n 99 1 -1 [print [
bottles n "of beer on the wall" crlf
bottles n "of beer" crlf
"Take one down, pass it around" crlf
bottles n - 1 "of beer on the wall" crlf
]]
Output (selected highlights):
99 bottles of beer on the wall 2 bottles of beer on the wall
99 bottles of beer 2 bottles of beer
Take one down, pass it around Take one down, pass it around
98 bottles of beer on the wall 1 bottle of beer on the wall
...Continues... 1 bottle of beer on the wall
1 bottle of beer
Take one down, pass it around
no bottles of beer on the wall
[edit] Ruby
plural = 's'
99.downto(1) do |i|
puts "#{i} bottle#{plural} of beer on the wall,"
puts "#{i} bottle#{plural} of beer"
puts "Take one down, pass it around!"
plural = '' if i - 1 == 1
if i > 1
puts "#{i-1} bottle#{plural} of beer on the wall!"
puts
else
puts "No more bottles of beer on the wall!"
end
end
Ruby has variable traces, so we can do
trace_var :$bottle_num do |val|
$bottles = %Q{#{val == 0 ? 'No more' : val.to_s} bottle#{val == 1 ? '' : 's'}}
end
($bottle_num = 99).times do
puts "#{$bottles} of beer on the wall"
puts "#{$bottles} of beer"
puts "Take one down, pass it around"
$bottle_num -= 1
puts "#{$bottles} of beer on the wall"
puts ""
end
[edit] Scala
[edit] Scheme
Works with: Chicken Scheme
(define (bottles x)
(format #t "~a bottles of beer on the wall~%" x)
(format #t "~a bottles of beer~%" x)
(format #t "Take one down, pass it around~%")
(format #t "~a bottles of beer on the wall~%" (- x 1))
(if (> (- x 1) 0)
(bottles (- x 1))))
[edit] Seed7
$ include "seed7_05.s7i";
const proc: main is func
local
var integer: number is 0;
begin
for number range 99 downto 2 do
write( number <& " bottles of beer on the wall, ");
writeln( number <& " bottles of beer.");
write( "Take one down and pass it around, ");
writeln( pred(number) <& " bottles of beer on the wall.");
writeln;
end for;
writeln("1 bottle of beer on the wall, 1 bottle of beer.");
writeln("Take one down and pass it around, no more bottles of beer on the wall.");
writeln;
writeln("No more bottles of beer on the wall, no more bottles of beer.");
writeln("Go to the store and buy some more, 99 bottles of beer on the wall.")
end func;
[edit] Slate
n@(Integer traits) bottleVerse
[| nprinted |
nprinted: n printString ; ' bottle' ; (n > 1 ifTrue: ['s'] ifFalse: ['']) ; ' of beer'.
inform: nprinted ; ' on the wall.'.
inform: nprinted.
inform: 'Take one down, pass it around.'.
inform: nprinted ; ' on the wall.'.
].
x@(Integer traits) bottles
[
x downTo: 0 do: #bottleVerse `er
].
99 bottles.
[edit] Smalltalk
A straightforward approach:
Smalltalk at: #sr put: 0 ; at: #s put: 0 !
sr := Dictionary new.
sr at: 0 put: ' bottle' ;
at: 1 put: ' bottles' ;
at: 2 put: ' of beer' ;
at: 3 put: ' on the wall' ;
at: 4 put: 'Take one down, pass it around' !
99 to: 0 by: -1 do: [:v | v print.
( v == 1 ) ifTrue: [ s := 0. ]
ifFalse: [ s := 1. ].
Transcript show: (sr at:s) ; show: (sr at:2) ; show: (sr at:3) ; cr.
v print.
Transcript show: (sr at:s) ; show: (sr at:2) ; cr.
(v ~~ 0) ifTrue: [ Transcript show: (sr at:4) ; cr. ].
].
[edit] SNUSP
/=!/===========!/==+++++++++# +9
| | /=!/=====@/==@@@+@+++++# +48 (itoa)
| | | | /==!/==@@@@=++++# +32 (space)
| | | | | \==@@++\!+++++++++++++\!+++++\
9 9 '9 9' space 'b' 'o' 't'
$@/>@/>@/>@/>@/>========@/>============@/>====@/>++++++++++ \n setup
/====================================loop=====>\!=>\!<<<<<<<< /
\@\@\>cr.@\< ?\<->+++++++++>->+++++++++\ | |
! | | \===-========>=>-==BCD==!\< @\< ?/< ?/# no more beer!
/=|=====|================================/
| | \<++t.<<----a.>----k.<++++e.<_.>>++++o.-n.< e.<_.>-d.>+o.>+++w.<-n.<<_.\
| | / /
| | \>---a.>n.<+++d.<_.>>++p.<---a.>>----s.s.<<<_.>>-------i.>+t.<<<_.\
| | / /
| | \>a.>>--r.<++++++o.>+++u.<-n.<+++d.>>>cr.<-T<+O<--B<<<#
| !
\@\<<<_.>>o.-n.<<_.>>>++t.<<+++h.---e.<_.>>>+++w.<<----a.>--l.l.>>CR.<---T<+++O<+B<<<#
|
\9.>9.>_.>B.>O.>T.t.<---l.<+++e.>>-s.<<<_.>>+++O.<+f.<_.>----b.+++e.E.>>-R.#
[edit] Standard ML
fun bottles 0 = ()
| bottles x = ( print (Int.toString x ^ " bottles of beer on the wall\n");
print (Int.toString x ^ " bottles of beer\n");
print "Take one down, pass it around\n";
print (Int.toString (x-1) ^ " bottles of beer on the wall\n");
bottles (x-1)
)
[edit] Tcl
[edit] TI-89 BASIC
Prgm
Local i,plural,clockWas,t,k,wait
"s" → plural
0 → k
isClkOn() → clockWas
Define wait() = Prgm
EndPrgm
ClockOn
For i,99,0,–1
Disp ""
Disp string(i) & " bottle" & plural & " of beer on the"
Disp "wall, " & string(i) & " bottle" & plural & " of beer."
getTime()[3]→t
While getTime()[3] = t and k = 0 : getKey() → k : EndWhile
If k ≠ 0 Then : Exit : EndIf
Disp "Take one down, pass it"
Disp "around."
getTime()[3]→t
While getTime()[3] = t and k = 0 : getKey() → k : EndWhile
If k ≠ 0 Then : Exit : EndIf
If i - 1 = 1 Then
"" → plural
EndIf
If i > 1 Then
Disp string(i-1) & " bottle" & plural & " of beer on the"
Disp "wall."
Else
Disp "No more bottles of beer on"
Disp "the wall."
EndIf
getTime()[3]→t
While abs(getTime()[3] - t)<2 and k = 0 : getKey() → k : EndWhile
If k ≠ 0 Then : Exit : EndIf
EndFor
If not clockWas Then
ClockOff
ENdIf
EndPrgm
[edit] UnixPipes
- Unix Pipes, avoiding all the turing complete sub programs like sed, awk,dc etc.
mkdir 99 || exit 1
trap "rm -rf 99" 1 2 3 4 5 6 7 8
(cd 99
mkfifo p.b1 p.b2 p.verse1 p.wall p.take
yes "on the wall" > p.wall &
yes "Take one down and pass it around, " > p.take &
(yes "bottles of beer" | nl -s\ | head -n 99 | tac | head -n 98 ;
echo "One bottle of beer";
echo "No more bottles of beer") | tee p.b1 p.b2 |
paste -d"\ " - p.wall p.b1 p.take | head -n 99 > p.verse1 &
cat p.b2 | tail -99 | paste -d"\ " p.verse1 - p.wall | head -n 99
)
rm -rf 99
[edit] UNIX Shell
Works with: Bourne Again SHell
#! /bin/bash
for((i=99; i >= 0; i--)); do
if [[ $i -gt 1 ]] || [[ $i -eq 0 ]]; then
s="s"
else
s=""
fi
echo "$i bottle$s of beer on the wall"
if [[ $i -ne 0 ]]; then
echo "$i bottle$s of beer
Take one down, pass it around"
fi
done
[edit] Ursala
#import nat
# each function takes a natural number to a block of text
quantity = # forms the plural as needed
~&iNC+ --' of beer'+ ~&?(
1?=/'1 bottle'! --' bottles'+ ~&h+ %nP,
'no more bottles'!)
verse =
^(successor,~&); ("s","n"). -[
-[quantity "s"]- on the wall, -[quantity "s"]-,
Take one down and pass it around, -[quantity "n"]- on the wall.]-
refrain "n" =
-[
No more bottles of beer on the wall, -[quantity 0]-.
Go to the store and buy some more, -[quantity "n"]- on the wall.]-
whole_song "n" = ~&ittt2BSSL (verse*x iota "n")--<refrain "n">
#show+
main = whole_song 99
[edit] V
[bottles
[newline <nowiki>''</nowiki> puts].
[beer
[0 =] ['No more bottles of beer' put] if
[1 =] ['One bottle of beer' put] if
[1 >] [dup put ' bottles of beer' put] if].
[0 =] [newline]
[beer ' on the wall, ' put beer newline
'Take one down and pass it around, ' put pred beer ' on the wall' puts newline]
tailrec].
99 bottles
[edit] VBScript
[edit] Simple Method
sub song( numBottles )
dim i
for i = numBottles to 0 step -1
if i > 0 then
wscript.echo pluralBottles(i) & " of beer on the wall"
wscript.echo pluralBottles(i) & " of beer"
if i = 1 then
wscript.echo "take it down"
else
wscript.echo "take one down"
end if
wscript.echo "and pass it round"
wscript.echo pluralBottles(i-1) & " of beer on the wall"
wscript.echo
else
wscript.echo "no more bottles of beer on the wall"
wscript.echo "no more bottles of beer"
wscript.echo "go to the store"
wscript.echo "and buy some more"
wscript.echo pluralBottles(numBottles) & " of beer on the wall"
wscript.echo
end if
next
end sub
function pluralBottles( n )
select case n
case 1
pluralBottles = "one bottle"
case 0
pluralBottles = "no more bottles"
case else
pluralBottles = n & " bottles"
end select
end function
song 3
Outputs:
3 bottles of beer on the wall
3 bottles of beer
take one down
and pass it round
2 bottles of beer on the wall
2 bottles of beer on the wall
2 bottles of beer
take one down
and pass it round
one bottle of beer on the wall
one bottle of beer on the wall
one bottle of beer
take it down
and pass it round
no more bottles of beer on the wall
no more bottles of beer on the wall
no more bottles of beer
go to the store
and buy some more
3 bottles of beer on the wall
[edit] Regular Expressions and Embedded Scripting
Another way of doing it, using Regular Expressions to locate executable code inside {} and replacing the code with the result of its evaluation.
function pluralBottles( n )
select case n
case 1
pluralBottles = "one bottle"
case 0
pluralBottles = "no more bottles"
case else
pluralBottles = n & " bottles"
end select
end function
function eef( b, r1, r2 )
if b then
eef = r1
else
eef = r2
end if
end function
Function evalEmbedded(sInput, sP1)
dim oRe, oMatch, oMatches
dim sExpr, sResult
Set oRe = New RegExp
'Look for expressions as enclosed in braces
oRe.Pattern = "{(.+?)}"
sResult = sInput
do
Set oMatches = oRe.Execute(sResult)
if oMatches.count = 0 then exit do
for each oMatch in oMatches
'~ wscript.echo oMatch.Value
for j = 0 to omatch.submatches.count - 1
sExpr = omatch.submatches(j)
sResult = Replace( sResult, "{" & sExpr & "}", eval(sExpr) )
next
next
loop
evalEmbedded = sResult
End Function
sub sing( numBottles )
dim i
for i = numBottles to 0 step -1
if i = 0 then
wscript.echo evalEmbedded("no more bottles of beer on the wall" & vbNewline & _
"no more bottles of beer" & vbNewline & _
"go to the store and buy some more" & vbNewline & _
"{pluralBottles(sP1)} of beer on the wall" & vbNewline, numBottles)
else
wscript.echo evalEmbedded("{pluralBottles(sP1)} of beer on the wall" & vbNewline & _
"{pluralBottles(sP1)} of beer" & vbNewline & _
"take {eef(sP1=1,""it"",""one"")} down and pass it round" & vbNewline & _
"{pluralBottles(sP1-1)} of beer on the wall" & vbNewline, i)
end if
next
end sub
sing 3
[edit] Visual Basic
Sub Main()
Const bottlesofbeer As String = " bottles of beer"
Const onthewall As String = " on the wall"
Const takeonedown As String = "Take one down, pass it around"
Const onebeer As String = "1 bottle of beer"
Dim bottles As Long
For bottles = 99 To 3 Step -1
Debug.Print CStr(bottles) & bottlesofbeer & onthewall
Debug.Print CStr(bottles) & bottlesofbeer
Debug.Print takeonedown
Debug.Print CStr(bottles - 1) & bottlesofbeer & onthewall
Debug.Print
Next
Debug.Print "2" & bottlesofbeer & onthewall
Debug.Print "2" & bottlesofbeer
Debug.Print takeonedown
Debug.Print onebeer & onthewall
Debug.Print
Debug.Print onebeer & onthewall
Debug.Print onebeer
Debug.Print takeonedown
Debug.Print "No more" & bottlesofbeer & onthewall
Debug.Print
Debug.Print "No" & bottlesofbeer & onthewall
Debug.Print "No" & bottlesofbeer
Debug.Print "Go to the store, buy some more"
Debug.Print "99" & bottlesofbeer & onthewall
End Sub
[edit] Visual Basic .NET
Platform: .NET
Module Module1
Sub Main()
Dim Bottles As Integer
For Bottles = 99 To 0 Step -1
If Bottles = 0 Then
Console.WriteLine("No more bottles of beer on the wall, no more bottles of beer.")
Console.WriteLine("Go to the store and buy some more, 99 bottles of beer on the wall.")
Console.ReadLine()
ElseIf Bottles = 1 Then
Console.WriteLine(Bottles & " bottle of beer on the wall, " & Bottles & " bottle of beer.")
Console.WriteLine("Take one down and pass it around, no more bottles of beer on the wall.")
Console.ReadLine()
Else
Console.WriteLine(Bottles & " bottles of beer on the wall, " & Bottles & " bottles of beer.")
Console.WriteLine("Take one down and pass it around, " & (Bottles - 1) & " bottles of beer on the wall.")
Console.ReadLine()
End If
Next
End Sub
End Module
[edit] X86 assembly
Using Windows/MASM32.
.386
.model flat, stdcall
option casemap :none
include \masm32\include\kernel32.inc
include \masm32\include\masm32.inc
include \masm32\include\user32.inc
includelib \masm32\lib\kernel32.lib
includelib \masm32\lib\masm32.lib
includelib \masm32\lib\user32.lib
.DATA
buffer db 1024 dup(?)
str1 db "%d bottles of beer on the wall.",10,13,0
str2 db "%d bottles of beer",10,13,0
str3 db "Take one down, pass it around",10,13,0
str4 db "No more bottles of beer on the wall!",10,13,0
nline db 13,10,0
bottles dd 99
.CODE
start:
INVOKE wsprintfA, offset buffer, offset str1, [bottles]
INVOKE StdOut, offset buffer
INVOKE wsprintfA, offset buffer, offset str2, [bottles]
INVOKE StdOut, offset buffer
INVOKE StdOut, offset str3
DEC [bottles]
INVOKE wsprintfA, offset buffer, offset str1, [bottles]
INVOKE StdOut, offset buffer
INVOKE StdOut, offset nline
CMP [bottles], 1
JNE start
INVOKE StdOut, offset str4
INVOKE ExitProcess, 0
end start







