December 31, 2014

Unconditional FizzBuzz

Ah FizzBuzz, the age old programming interview question. For those of you that don't know what FizzBuzz is, here's a quick rundown:

For numbers 1 through 100

  • if the number is divisible by 3, print "Fizz"
    • if the number is divisible by 5, print "Buzz"
    • if the number is divisible by 3 and 5, print "FizzBuzz"
    • otherwise, print the number

Seems easy right? You'd be surprised at how many people can't do this. I'd probably be surprised too if I hadn't sat on the interviewing side of the table at my previous placement when they were looking for their next co-op student.

A basic solution in Clojure could be as follows:

(map #(cond (zero? (mod % 15)) "FizzBuzz"
            (zero? (mod % 5)) "Buzz"
            (zero? (mod % 3)) "Fizz"
            :else %)
     (range 1 101))

Now in my previous post I talked about Project Euler and how you can solve the problems in numerous different ways. The same goes for FizzBuzz.

Some popular modifications to the FizzBuzz challenges include: writing the solution recursively, writing it in just one (reasonably long) line of code, using different paradigms, etc. A friend of mine actually mentioned this particular one to me and I thought it was slightly more interesting than the alternatives I've been presented with so far - the unconditional FizzBuzz.

In other words, write FizzBuzz without using any conditionals such as if or cond. Of course I wrote my solution in Clojure. It's so handy for manipulating data :)

(let [words [nil "Fizz" "Buzz" "FizzBuzz"]
      fizz [1 0 0]
      buzz [2 0 0 0 0]]
     (map #((assoc words 0 %) (+ (fizz (rem % 3)) (buzz (rem % 5))))
          (range 1 101)))

You could write this in one line if you wanted to by getting rid of that let statement but of course, that removes some of the readability.

(map #((assoc [nil "Fizz" "Buzz" "FizzBuzz"] 0 %) (+ ([1 0 0 ] (rem % 3)) ([2 0 0 0 0] (rem % 5)))) (range 1 101))

The one liner version of this solution is Twitter friendly as well - 113 characters :)

ps. for extra laughs see FizzBuzz - The Enterprise Edition

Tags: clojure