Jump to content
Banner by ~ Kyoshi Frost Wolf
  • entries
    17
  • comments
    151
  • views
    17,736

The Fizz Buzz test and solutions


Killian Jones

1,406 views

So on Codecademy, in one of the tracks, you have to solve FizzBuzz. A simple test to see if you can write some of the easy loops and conditional structures in a language.

 

Fizz Buzz is a game, where you count the numbers, but if a number is divisible by 3 you say "Fizz" and when it is divisible by 5 you say "Buzz". If divisible by both you say "FizzBuzz".

 

Now their solution is slightly annoying to me as it isn't very elegant and just proposes a very nested if structure. See code below.

var end = 20;for (var i = 1; i <= end; i++){	if (i%15 === 0) 	{		console.log("FizzBuzz");	}	else	{		if (i%5 === 0)		{			console.log("Buzz");		}		else		{			if (i%3 === 0)			{				console.log("Fizz");			}			else			{				console.log(i);			}		}	}}

 

It works, and it's ok, but it's not very extendable. I have my own solution which I find nicer:

 

var end = 20;for (var i = 1; i <= end; i++){	var word = "";		if(i%3 === 0)	{		word += "Fizz";	}	if(i%5 === 0)	{		word += "Buzz";	}		if(word != "")	{		console.log(i);	}	else	{		console.log(word);	}}

 

Why do I like my solution? It uses three if statements but doesn't intend to. It doesn't nest any structures cause it doesn't need to. check for both at the same time ever. Another thing is, if the game were extended somehow, like say "Wizz" for every number divisible by 7. My solution easily allows a single if to be popped in. The proposed solution will need a completely rewrite.

 

Bottom line is, i don't like it.

  • Brohoof 2

4 Comments


Recommended Comments

Pfffft.

print [("FizzBuzz" if x%15==0 else ("Fizz" if x%3==0 else ("Buzz" if x%5==0 else x))) for x in range(1,101)]

Python, Tichbaby, Python is what you neeeed.
  • Brohoof 1
Link to comment

Derp! Yeah, that's right actually. ; _ ;

 

I forgot! D:

 

Well, how are you liking it so far? :3

Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Join the herd!

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...