So: much like Marcel Proust biting into a madelaine, when I read this quiz on
Friday I had a rush of old memories. I have never heard of fizzbuzz being
used as a recruitment technique before, however, I am familiar with it
because back in high school we played it as a drinking game. If we were
feeling particularly hardcore we would also add in 'Bang' for multiples of 7.
I had as much as forgotten about fizzbuzz as I haven't though about it in
over twelve years or so...
Anyway, I have deviated from the official spec in a few ways here. First of
all, I saw no reason to stop at 100, so my solution will print results for
any user-specified 'n'. Rather than golfing, which I am no good at, I decided
to go with an obvious solution.
The second deviation is that because the solution is fairly short (ie: about a
paragraph) I thought it would be interesting to write solutions in a few
other languages as a point of comparison. To that end I also wrote solutions
in Python, Lua, Scheme, and plain old C. Hopefully you can forgive me some
off-topicness for posting these as well.
On with the code:
# fizz.rb
1.upto(ARGV[0].to_i) do |n|
if n % 15 == 0
print "FizzBuzz "
elsif n % 5 == 0
print "Buzz "
elsif n % 3 == 0
print "Fizz "
else print "#{n} "
end
end
puts
# fizz.py
import sys
for n in range(1,int(sys.argv[1])+1):
if n % 15 == 0:
sys.stdout.write("FizzBuzz ")
elif n % 3 == 0:
sys.stdout.write("Fizz ")
elif n % 5 == 0:
sys.stdout.write("Buzz ")
else: sys.stdout.write("%i " % n)
print
-- fizz.lua
for n=1,arg[1] do
if n % 15 == 0 then
io.write("FizzBuzz ")
elseif n % 3 == 0 then
io.write("Fizz ")
elseif n % 5 == 0 then
io.write("Buzz ")
else
io.write(n .. " ")
end
end
print()
/* fizz.c */
#include <stdio.h>
int main(int argc, char *argv[]) {
int i;
for (i = 1; i <= atoi(argv[1]); i++) {
if (i % 15 == 0)
printf("%s ", "FizzBuzz");
else if (i % 3 == 0)
printf("%s ", "Fizz");
else if (i % 5 == 0)
printf("%s ", "Buzz");
else
printf("%i ", i);
}
printf("\n");
return 0;
}
;;; fizz.scm
(define (fizz x)
(define (mod5? n)
(if (eq? (modulo n 5) 0) #t #f))
(define (mod3? n)
(if (eq? (modulo n 3) 0) #t #f))
(define (fizz-iter n x)
(cond
((> n x) (newline) #t)
((and (mod3? n) (not (mod5? n))) (display "Fizz ")
(fizz-iter (+ n 1) x))
((and (mod5? n) (not (mod3? n))) (display "Buzz ")
(fizz-iter (+ n 1) x))
((and (mod5? n) (mod3? n)) (display "FizzBuzz ")
(fizz-iter (+ n 1) x))
(else (display n) (display " ")
(fizz-iter (+ n 1) x))))
(fizz-iter 1 x))
cheers,
-d
--
darren kirby :: Part of the problem since 1976 :: http://badcomputer.org
"...the number of UNIX installations has grown to 10, with more expected..."
- Dennis Ritchie and Ken Thompson, June 1972