Tuesday, January 26, 2016

The FizzBuzz

http://blog.codinghorror.com/why-cant-programmers-program/

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".

#!/usr/bin/env ruby
(1..100).each do |i|
   if( i % 3 == 0 && i % 5 != 0 )
      p "Fizz"
   elsif( i % 5 == 0 && i % 3 != 0 )
      p "Buzz"
   elsif( i % 5 == 0 && i % 3 == 0 )
      p "FizzBuzz"
   else
      p i
   end
end 


Seems like there should be a more elegant solution to this.  But this only took about 2 minutes to do.  Arg, now I'm curious to know if this would have passed the test!  Ahh well, guess I'll just stuff this in the corner for future reference.

No comments:

Post a Comment