Wednesday, May 20, 2015

FizzBuzz Solved

To solve FizzBuzz we started with a for loop from FizzBuzz Part 1, added an if else statement from FizzBuzz Part 2, now we will finish off with the logic and math to proclaim this FizzBuzz Solved.  I know, just reading it get me a little amped.

for (i = 1; i<=20; i++){
    if (i%15==0)                              This says take i and if you divide by 15 and there is no remainder
    { console.log("FizzBuzz")         puts FizzBuzz to the console.
    }
    else if (i%5==0)                         This says take i and if you divide by 5 and there is no remainder
    { console.log("Buzz")                puts Buzz to the console.
    }
    else if (i%3==0                          This says take i and if you divide by 3 and there is no remainder
    { console.log("Fizz")                 puts Fizz to the console.
    }
    else                                            Otherwise
    {
    console.log(i);                           puts i to the console.
    }
}

Ok so did I do it as cleanly as it looks right there... uh sure I did.

What why don't you believe me ... because you know me right.






Yeah it wasn't that easy.  I started with if i%3==0; "Fizz".  It worked, then when I added %5; Buzz, it both worked and didn't work which equals "Failure".  So I had to figure out that I needed to add else if because I have two conditions; %3 and %5.  Then when I added %15; Fizz buzz... you guessed it! Whomp whomp whomp.  I had to reverse the order from 3,5,15 to 15,5,3.
You said  
Whaaat?

I said
Yeah it didn't make sense, but if you squint and think about it, then it will.

Let me explain.  The condition has to check for (i%15==0) first because if it doesn't it will log Fizz on i=15 because it comes to that bit of code first.  It will never log FizzBuzz because 15 satisfies if (i%3==0) which is first on the stack.

So by putting (i%15==0) first, it will log "FizzBuzz" then for every other number it will log the correct fizz or buzz.
Wow it is so clear to me now.  Don't worry if it isn't clear yet, just re-read this blog or start again from the first FizzBuzz Part 1. (That's the one with Morpheus)

This tutorial shows just one of many ways to solve FizzBuzz.  Each language has one as well.  I think a good coder should be able to write FizzBuzz in each language s/he is proficient in.

Brought to you by KENYACODE, Can you code?

No comments:

Post a Comment