Friday, February 03, 2006

 

99 Bottles of Beer Example

I read Roger's challenge to write a brief version of the old "99 Bottles" program. If one isn't too fussy about formatting, it can be done in Eiffel in lessa than 20 lines.


class NINETY_NINE create make

feature make is
local
i: INTEGER
do
from i := 99 until i <= 1 loop
print(i.out + " bottles of beer on the wall, " +
i.out + " bottles of beer!%NTake one down, pass it around, " +
(i-1).out + " bottles of beer on the wall!%N%N")
i := i - 1
end
print("One bottle of beer on the wall, one bottle of beer!%N" +
"Take it down, pass it around, no more bottles of beer on the wall!%N%N" +
"No more bottles of beer on the wall, no more bottles of beer!%N" +
"Go to the store, buy some more, 99 bottles of beer on the wall!%N")
end
end


Of course, if the real point of this is to lampoon programming, and OO programming, then it seems to me that the original example (cited by Roger and over one hundred lines) doesn't go far enough! After all, it lacks a store class, and a wall class, and singer classes, and of course there the shelf class really needs to be a deferred class and the shelf variable dynamically bound to an ARRAYED_SHELF[ANY].

Or something like that.

Comments:
Looks good, Greg!

Your next challenge is to write a matching ACE file that is no longer than the program itself :-)
 
Here's my recursive solution. Sorry about the tilde characters; I can't get Blogger to accept nonbreaking spaces or the pre tag in comments.

class NINETY_NINE create make feature
~~~make is do bottles(99) end
~~~bottles(i: INTEGER) is do
~~~~~~print(i.out + " bottles of beer on the wall, " +
~~~~~~~~~i.out + " bottles of beer!%NTake one down, pass it around, " +
~~~~~~~~~(i-1).out + " bottles of beer on the wall!%N%N")
~~~~~~if i > 1 then
~~~~~~~~~bottles(i - 1)
~~~~~~else
~~~~~~~~~print("One bottle of beer on the wall, one bottle of beer!%N" +
~~~~~~~~~~~~"Take it down, pass it around, no more bottles of beer on the wall!%N%N" +
~~~~~~~~~~~~"No more bottles of beer on the wall, no more bottles of beer!%N" +
~~~~~~~~~~~~"Go to the store, buy some more, 99 bottles of beer on the wall!%N")
~~~~~~end
~~~end
end
 
Missing loop invariant.
 
Remember that structured programming is sometimes (often?) superior to OO programming!
 
Post a Comment



<< Home

This page is powered by Blogger. Isn't yours?