/ programming

Fizzbuzz

I found out about the "FizzBuzz" test for programmers today. It is a test that some companies use to make sure the people they're hiring for programming positions can actually program. Apparently a vast number of applicants can't even pass this simple test! The question is as follows:

Write a program that prints the numbers from 1 to 100. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz".

Since I've been brushing up on my C++ skills by taking a couple of classes on modern C++11, I decided to have a try and came up with the smart-ass answer below:

#include <iostream>

int main(void) {
    for (int i = 1; i < 101; i++)
        std::cout << i
                  << (i % 3 ? "" : "\b\b\bFizz   ")
                  << (i % 5 ? "" : "\b\b\bBuzz")
                  << std::endl;
    return 0;
}

Since I write more Scheme code than C++, I had another go at it using Scheme, with the even more smart-ass solution below. It looks complicated because I solved it the hard way, by creating a generator that will give you the next FizzBuzz ad infinit. Then I map it over a range of numbers to just get the first 100.

For some reason, in my DrRacket there was no range operation, so I had to write that one as well. (Using a range with a generator kind of defeats the purpose, but this was just an exercise)

(define (fizzbuzz)
  (define call/cc call-with-current-continuation)
  (define (stream-fizzbuzz return)
    (let loop ((n 1))
      (set! return (call/cc (lambda (continue-here)
         (set! stream-fizzbuzz continue-here)
         (return (or (and (= (remainder n 15) 0) 'fizzbuzz)
                     (and (= (remainder n  3) 0) 'fizz)
                     (and (= (remainder n  5) 0) 'buzz)
                     n))
      )))
      (loop (+ n 1))
    ) 
  )
  (define (generator) (call/cc stream-fizzbuzz))

  (define (range start end)
    (if (> start end)
      '()
      (cons start (range (+ start 1) end)))
  )

  (map (lambda (x) (generator)) (range 1 100))
)