Sunday, September 5, 2010

FizzBuzz - Pt. 1

It seems there is a party game out there called "Fizz Buzz".  It works like this:  All the players, in turn, count from one to whatever.  Except, that if the player's number is divisible by 3, the player says "Fizz" rather than the number.

Further exception:  If the number is divisible by 5, the player says "Buzz" rather than the number.

The observant observer will be wondering what to do is the number is divisible by 15.  And, the answer is, to say "FizzBuzz".   In other words, a typical 7 player game (with the usual players) would go something like:

Fred: One
Sam: Two
Gerta: Fizz
Jennifer: Four
George: Buzz
Frank:  Fizz
Tildy:  Seven

Fred: Eight
Sam: Fizz
Gerta: Ten
Everybody:  You Loose!

Weird game.  However, my son mentioned to me that it has become a screening test for programmers:  If the applicant cannot sketch a valid program in 15 lines or so, the applicant gets rejected.  Naturally, I wondered how one could do this in Oracle.  20 minutes later I had written this:


  1  select candidate,
  2        decode (mod(candidate,15),0,'FizzBuzz',
  3                 (decode(mod(candidate,3),0,'Fizz',
  4                      (decode(mod(candidate,5),0,'Buzz',candidate)
  5  )    )         )     )
  6    from (select level candidate
  7             from dual
  8             connect by level < 101
  9     )

With this result:

         1 1
         2 2
         3 Fizz
         4 4
         5 Buzz
         6 Fizz
         7 7
         8 8
         9 Fizz
        10 Buzz
        11 11
        12 Fizz
        13 13
        14 14
        15 FizzBuzz
        16 16
        17 17





But why stop here?  My next thought was how this would look in a procedural language?  So, I tried a little bit of awk:


function mymod(n,m,   returning) {
       returning = n - m*int(n/m)
       return returning
  }
BEGIN  {
  for (i=1; i<=100; i++) {
      if (mymod(i,15) == 0)  printf "%5d %10s \n",  i,  "  FizzBuzz"
          else if(mymod(i,3) == 0)  printf "%5d %10s \n",  i, "  Fizz  "
             else if(mymod(i,5) == 0)  printf "%5d %10s \n",  i, "  Buzz  "
                else  printf "%5d %7d \n",   i, i
  }
}

The purpose for the function was to cover the case where the language did not contain a 'mod' function. Most every language I know has either a 'mod' function, or knows how to truncate to an integer.




So, FizzBuzz is solved.  But, there is more to come.....