The Fizz Buzz test and solutions
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.
-
2
4 Comments
Recommended Comments
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