One developer interview question is asked or referred to so often for so long, it is almost a cliché: the FizzBuzz challenge. Though this challenge will appear very simplistic to those with some coding experience, it is designed to weed out people who cannot creatively use their coding knowledge to solve simple problems. See our thread on the rationale behind coding challenges for more info.
##The History of the FizzBuzz Challenge
As the inventor of this challenge, Imran Ghory, states:
After a fair bit of trial and error I’ve come to discover that people who struggle to code don’t just struggle on big problems, or even smallish problems (i.e. write a implementation of a linked list). They struggle with tiny problems.
So I set out to develop questions that can identify this kind of developer and came up with a class of questions I call “FizzBuzz Questions” named after a game children often play (or are made to play) in schools in the UK.
This challenge is based on a children’s game used to teach division. Children sit in a circle. The player going first will say one, followed by the player next to them (going clockwise or counter-clockwise) saying two, and so on, adding one each time. However, any number divisible by three is replaced by the word Fizz, any divisible by five by the word Buzz, and numbers divisible by both three and five become FizzBuzz. A player who hesitates or makes a mistake is eliminated from the game.
##The Challenge
Turned into a code challenge, this becomes the FizzBuzz Challenge:
"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.
Try your hand at the FizzBuzz challenge: submit your answer below! It’s not a true test of your abilities if you look at other people’s answers below or Google for examples - try to solve this yourself as if you were in a job interview situation.
for ( var numbers = 1; numbers <= 100; numbers++) { //Lists numbers to 100
if (numbers % 15 === 0 ) { //if number is divisible by 5 or 3 prints FizzBuzz
console.log("FizzBuzz") }
else if (numbers % 5 === 0) { //if number is divisible by 5 prints Buzz
console.log("Buzz") }
else if (numbers % 3 === 0 ) { //if number is divisible by 3 prints Fizz
console.log("Fizz") }
else {
console.log(numbers) } // if neither prints the number
}
I’m curious what other languages can do this more efficiently.
Interesting thing is there is an old Codecademy lesson on the FizzBuzz challenge: https://www.codecademy.com/courses/fizzbuzz/0/1 And while old might could help people get in the right direction with creating their own version of the FizzBuzz challenge!
Also, I believe there is one answer that works granted but I don’t think would be acceptable in this challenge:
print('1,2,Fizz,4,Buzz,Fizz,7,8,Fizz,Buzz,11,Fizz,13,14,FizzBuzz,16,17,Fizz,19,Buzz,Fizz,...') Etc. Etc.
And I would know because I was lazy on my first FizzBuzz excersize in Javascript and well…might have of done that puts on cone of shame Thankfully I had the consciousness to go back and basically figure out and came up with a code very similar to @oscartbeamish
Here is an attempt at the current challenge. Thinking about how real children play (at least, the way I did), they keep an eye on the child three places before them and five places: if they say Fizz or Buzz respectively, then that is what the child has to say.
Therefore, the program has to keep track of the last five responses, and repeat the n-minus-third (if it’s a fizz) and/or the n-minus-fifth (if it’s a buzz); otherwise just say the number.
There’s no modulus operations: except one but that is just to prettify the output!
#!/usr/bin/python3
def Rotate(arr, string):
return [string] + arr[:4]
lastanswers=['Buzz', ' 4', 'Fizz', ' 2', ' 1']
for a in lastanswers[::-1]:
print(a, end=' ')
n = 6
for n in range(6,101):
ans = ''
if 'Fizz' in lastanswers[2] : ans += 'Fizz'
if 'Buzz' in lastanswers[4] : ans += 'Buzz'
if len(ans)==0 : ans = "{:3}".format(n)
print(ans, end=" ")
lastanswers = Rotate(lastanswers, ans)
if n % 15 == 0 : print()
print()
The Rotate() function moves the list of answers down one, and adds the new answer at the head of the list.
The list lastanswers contains the five most recent answers. It’s preloaded with the first five, so the first job is to print these out (in reverse).
From 6 onwards, we just check the previous answers and work out the new answer: print it out and save it in the list.
x = 1
a = []
while (x <= 100):
a.append(x)
x = x + 1
#above code just makes a list of 1-100
for i in a:
if (i % 5 == 0 and i % 3 == 0):
print ("FizzBuzz")
elif (i % 5 == 0):
print("Buzz")
elif (i % 3 == 0):
print("Fizz")
else:
print(i)
Here is my answer in Python3. The code is pretty much self explanatory with the comments.
def printNumbers():
num = list(range(1,101))
for i in range(len(num)):
if num[i]%3 == 0 and num[i]%5 == 0: # test if a number is disivible by both 3 and 5 (ie. remainder is 0)
num[i] = "FizzBuzz"
elif num[i]%3 == 0: # test if a number is divisible by 3
num[i] = "Fizz"
elif num[i]%5 == 0: # test if a number is divisible by 5
num[i] = "Buzz"
return num # return the list
Because indices start at 0 , the value is ++idx(incremented) before the first comparison is made
That does not affect the function call idx is a parameter for the function, so the next call gets the sequential index nr
print ["Fizz"*(num % 3 == 0) + "Buzz"*(num % 5 == 0) or num for num in range(1, 101)]
I use the concept that the boolean expressions can be turned into 0s and 1s. 0 being False and 1 being True. So if one of them is false, they become an empty string such as let’s say a number is divisible by 5 and not 3:
If both are true, the Fizz and Buzz are concatenated together. If non of them are true, they both become empty strings and well…the number is returned instead.
Another way to write this is:
print ["Fizz"*(not num % 3) + "Buzz"*(not num % 5) or num for num in range(1, 101)]
A basic for loop with a nested if as others have used. The equality check for mod 3 and mod 5 needs to come first because an if statement will stop at the first true result/evaluation.
for i in range(1,101):
if (i % 3 == 0) and (i % 5 == 0):
print(i, 'fizzbuzz')
elif i % 3 == 0:
print(i, 'fizz')
elif i % 5 == 0:
print(i, 'buzz')
else:
print(i)
#!/usr/bin/env perl
use warnings;
use strict;
use v5.10;
sub main {
say fizzbuzz($_) for 1..100;
}
sub fizzbuzz {
my $i = shift;
if ( not $i%15 ) { return "FizzBuzz"}
elsif ( not $i%5 ) { return "Buzz" }
elsif ( not $i%3 ) { return "Fizz" }
else { return $i }
}
#Call main()
main();