Fizz-Buzz or Bizz Buzz is a word game, popularized by Jeff Atwood in the article:
Why Can’t Programmers… Program?
The game has been turned into a simple programming test:
Write a program that prints the numbers from 1 to 100. But for multiples of 3 print "Fizz" instead of the number and for the multiples of 5 print "Buzz". For numbers which are multiples of both 3 and 5 print "FizzBuzz".
If you’re involved in hiring programmers then the article is probably worth a read.
This kind of problem can be expressed very concisely in functional programming languages to the point where the code fits in a tweet.
Haskell
Last month Calvin Bottoms posted an article describing and implementation of Fizz-Buzz in Haskell expressed in a mere 78 characters:
[max(show x)(concat[n|(f,n)<-[(3,"Fizz"),(5,"Buzz")],mod x f==0])|x<-[1..100]]
Higher order functions and list comprehensions (a feature taken from Miranda) make this very terse, but also a little impenetrable.
F#
Rather more verbose (122 characters) but perhaps a little more readable:
for n in 1..100 do printfn "%s" <| match n%3, n%5 with
0,0 -> "FizzBuzz" | 0,_ -> "Fizz" | _,0 -> "Buzz" | _,_ -> string n
Pattern matching makes the various states relatively obvious.
Clojure
Martin Trojer sent over this quite elegant Clojure implementation via Twitter:
(map #(cond (zero? (mod % 15)) "FizzBuzz" (zero? (mod % 3)) "Fizz"
(zero? (mod % 5)) "Buzz" :else %) (range 1 101))
Testing for “FizzBuzz” using modulus 15 helps reduce the character count.
Erlang
I’ve been playing with Erlang recently and Fizz-Buzz is my new “Hello World” app. This was my first effort:
f(101)->ok;
f(X)->Y=case{X rem 3,X rem 5}of{0,0}->fizzbuzz;{0,_}->fizz;{_,0}->buzz;
{_,_}->X end,io:format("~w~n",[Y]),f(X+1).
Erlang doesn’t have a for loop construct built-in so I resorted to recursion instead.
That said you can achieve the same thing using the lists module seq and foreach functions:
lists:foreach(fun(X)->io:format("~w~n",[case{X rem 3,X rem 5}of{0,0}->fizzbuzz;
{0,_}->fizz;{_,0}->buzz;{_,_}->X end])end,lists:seq(1,100)).
Next?
Is Fizz-Buzz the new “Hello World”?
I think it might be, despite Jeff’s protestations, take a peek at Fizz-Buzz on Rosetta Code.