Jonathan. Frech’s WebBlog

99 Bottles of Beer (#144)

Jonathan Frech,

I recently⁠¹ found a five year old StackExchange thread talking about a programming challenge to recreate the marvelously imaginative lyrics of “99 Bottles of Beer”. The song goes as follows (whole lyrics can be viewed below).

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.

[…]

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.

Of course, the real challenge is not to build a pro­gram that generates the lyrics but rather to do it with the least amount of characters⁠². To achieve this goal, I tried out var­i­ous strategies, all writ­ten in Python.

The first strat­e­gy is to join a string gen­er­ated by a for loop (263 characters).

((listing))

The second, less efficient strat­e­gy is to use a func­tion and recursion (274 characters).

((listing))

The third is a bit more character-efficient, using lambda functions and recursion (270 characters).

((listing))

The fourth, final and most space-efficient⁠³ strat­e­gy is to use a while loop (250 characters).

((listing))

[1][2020-07-21] One may note that I at the time of this post was not a codegolf.StackExchange member.
[2][2020-07-27] N. b.: A source file’s trailing newline does not count towards the golf score.
[3][2020-07-21] That I came up with at that time.