[Challenge] The Classic FizzBuzz Challenge

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.

Remember to format your code!

2 Likes

JavaScript all the way!


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.

2 Likes

This is not an entry, but two example cases (JavaScript) for learners to study…

function fizzbuzz(lim) {
  var i = 0, j;
  while (i < lim) {
    i++;
    switch (0) {
      case i % 15: j = 'FizzBuzz'; break;
      case i % 3: j = 'Fizz'; break;
      case i % 5: j = 'Buzz'; break;
      default: j = i.toString();
    }
    console.log(j);
  }
}

function FizzBuzz(lim) {
  var i = 0, j;
  while (i < lim) {
    i++;
    j = "";
    j += i % 3 ? '' : 'Fizz';
    j += i % 5 ? '' : 'Buzz';
    console.log(j ? j : i.toString());
  }
}
10 Likes

Thanks for this Roy, I was just trying to figure out how to solve the challenge using a switch. Your examples are very helpful.

5 Likes

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! :smiley:

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

6 Likes

Hi all,

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.

I think that’s all for now.

Tim F

9 Likes
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)
4 Likes
for x in range(1,101): 
  if x % 3 == 0 and x % 5 == 0:
      print 'FizzBuzz'
 elif x % 3 == 0: 
      print 'Fizz'
 elif x % 5 == 0:
     print 'Buzz'
 else: 
     print x
5 Likes
<?php
        for($i=1; $i<=100; $i++){
            if($i%15==0){
                  echo 'FizzBuzz</br>';
            }elseif($i%5==0){
                  echo 'Buzz</br>';
            }elseif($i%3==0){
                  echo'Fizz</br>';
            }else{
                echo $i.'</br>';
            }
        }
      ?>

This is the same piece of code of Oscar Beamish but written in php…

2 Likes

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 
3 Likes

I’m learning JavaScript :grin: So, this is my solution:

const FizzBuzz2 = function() {
	const arr = [];
	arr.length = 100;
	for(let i = 1; i <= arr.length; i++) {
		arr[i-1] = ((i % 3) ? '' : 'Fizz') + ((i % 5) ? '' : 'Buzz') || i;
	}
	return arr.join(', ');
};

console.log(FizzBuzz2());
2 Likes

JavaScript

for (var nr = 1; nr < 101; nr++) {
    var str = (nr % 3 ? '' : 'Fizz') + (nr % 5 ? '' : 'Buzz');
    console.log(nr, str == '' ? nr : str);
}

same concept, better minification:

for(var nr=1 , empty='' ; nr<101; nr++){
    var str = (nr % 3 ? empty : 'Fizz')  +  (nr % 5 ? empty : 'Buzz')
    console.log( nr , str==empty ? nr : str);
}

Using the Array index and ES6
Array.from(new Array(100),(unused,idx)=>{
    var str = (++idx % 3 ? '' : 'Fizz') + (idx % 5 ? '' : 'Buzz')
    return str == '' ? idx : str;
});

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

3 Likes

OK this was slightly more challenging than I thought but I haven’t gone to university yet but the below was my first attempt.

for x in range(1,101):
    if x % 3 == 0:
        print "Fizz"
    elif x % 5 == 0:
        print "Buzz"
    elif x % 3 and x % 5 == 0:
        print "Fizzbuzz"
    else:
        print x

Below is my second example which acctualy works its the same thing just re arranged and I added == 0 to the first if statement.

for x in range(1,101):
    if x % 3 == 0 and x % 5 == 0:
        print "Fizzbuzz"
    elif x % 3 == 0:
        print "Fizz"
    elif x % 5 == 0:
        print "Buzz"
    else:
        print x
2 Likes

Nice challenge, never heard of it around here. Could also have done this with switch case, but hey.

=]

<?php

for($i=1; $i<=100; $i++)
{
  if(($i%3 == 0) && ($i%5 == 0))
  {
    echo "FizzBuzz<br />";
  }
  elseif($i%3 == 0)
  {
    echo "Fizz<br />";
  }
  elseif($i%5 == 0)
  {
    echo "Buzz<br />";
  }
  else
  echo $i . "<br />";
}

 ?>
2 Likes

Hi all,
Not really a chalange, but for fun.
java again:

package ro.khrypt.codekata.codeacademy;
public class FizzBuzz {
    public static void main(String[] args) {
        for (int i = 1; i <= 100; i++) {
            if(i % 15 == 0){
                System.out.println("FizzBuzz");
            }else if(i % 5 == 0){
                System.out.println("Buzz");
            }else if(i % 3 == 0){
                System.out.println("Fizz");
            }else{
                System.out.println(i);
            }
        }
    }
}

Simple straight forward.

4 Likes
Array.from(new Array(100),(none,idx)=>{
    var str = (++idx % 3 ? '' : 'Fizz') + (idx % 5 ? '' : 'Buzz')
    return str == '' ? idx : str;
});

Shortened my previous code, because an empty string is a false value

JavaScript

Array.from({length:100},(none,idx)=>{
    return (++idx % 3 ? '' : 'Fizz')  +  (idx % 5 ? '' : 'Buzz')    ||    idx
});

Which can be shortened to:

Array.from({length:100},(n,i)=>(++i%3?'':'Fizz')+(i%5?'':'Buzz')||i);

7 Likes

Here’s a list comprehension way in Python:

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:

"Fizz" * 0 -> ""
"Buzz" * 1 -> "Buzz"
"" + "Buzz" -> "Buzz"

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)]

Realized this is similar to @javaslayer08029’s solution.

10 Likes

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)

2 Likes

An example from Perl language.

#!/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();
1 Like

Resolved with JavaScript:

var response = "";
for (var i = 1; i <= 100; i++){
    response = i % 3 === 0 ? "Fizz" : ''; //If mod 3, add 'Fizz' or blank
    response = i % 5 === 0 ? response + "Buzz" : response; //If mod 5, concatenate 'Buzz'
    response === '' ? console.log(i) : console.log(response); //If blank, print number
}
2 Likes