FizzBuzz is a famous interview test given to incoming developers, to make sure they can at least kindofsortof program. It asks the candidate to write a program that will print out the numbers 1 – 100 inclusively – except for multiples of 3 print “Fizz”, for multiples of 5 print “Buzz”, and for multiples of both print “FizzBuzz”.
I was introduced to this via my Skillcrush class for Ruby – so I wrote my first FizzBuzz test in Ruby.
Now that I’m (re-) working my way through vanilla JavaScript, I decided to give it a go in this language as well. And it only took me about 2 minutes! Which is great, I think the first one took me 20.
Now, whenever I’m bored or find myself with some idle time, I write a quick FizzBuzz program just to keep it sharp.
Here’s what I got for the FizzBuzz tests in both Javascript and Ruby – I hope someone finds it useful. Did you solve it differently? Post your answers in the comments below.
Javascript FizzBuzz Solution:
for (i = 1; i<=100; i++){ if ((i % 3 === 0) && (i % 5 === 0)){ console.log("FizzBuzz"); } else if (i % 3 === 0){ console.log("Fizz"); } else if (i % 5 === 0){ console.log("Buzz"); } else { console.log(i); }; };
Ruby FizzBuzz Solution
(1..100).each do |i| if (i % 15 === 0) puts "FizzBuzz" elsif (i % 3 === 0) puts "Fizz" elsif (i % 5 === 0) puts "Buzz" else puts i end end
See? Not too hard! Keep in mind there are multiple ways to do each one.
Best of luck FizzBuzzing!