Interview question : fizz buzz
January 26th, 2007 . by polyGeekInterview question: I was reading RaganWald’s blog and ran across this interesting tid-bit. The gist of the article is, “ask a very simple programing question that can be answered during a phone interview to weed out people who can’t program a lick.”
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 a lot of managers read RaganWald’s blog you just might get this yourself in your next interview. So heads up.
Here’s my very simple solution: (download some code)
So that essentially gets the results your looking for but it is very inefficient. The first thing you can do is place all that code in a function and it will run about 3 times faster. The reason for that is because local variables are stored in the chip cache and not in system RAM.
Then I started messing around with the code to see how fast I could get it to run. The first thing I did was take out the trace statements and substitute a counter in their place. I did this because I just want to see how fast the algorithm will run without introducing system noise from tracing to the output panel.
Here’s that code:
I messed around quite a bit, tried using some ternary operators and such but that didn’t help. I was came up with a way of removing the && conditional in the first if-statement by asking this: if( -fizz - buzz == 0) That produces the same count but didn’t make a significant change in the time it took to run through the loop.
Replacing the for-loop with a do-while also didn’t make a meaningful difference.
You know what did make a huge difference? Using AS3. “No duhhh”, right? :-)
The AS3 code ran roughly 21 times faster. Happy days.
I thought that making variables out of the modulus results in the beginning of the loops so that they only had to be calculated once would speed things up but again, not much, if any difference.
I’d love to see it if you can find a more optimized algorithm in Actionscript.




