Not one to pass up my chance at a good programming problem, I took a stab at FizzBuzz because it seemed, well, relatively simply to construct a solution.
Here’s my code on gist:
Second, I just iterated through the problem with a foor loop 100 times and at each step, I did three tests:
- Modulus the integer by 3. If it’s equal to zero (meaning the integer divides exactly by three with no remainder) then add “fizz” to a variable, p, which was set to “” (blank) at the beginning of each set of tests.
- Modulus the integer by 5 (same gameshow as above, just round 2). If this is equal to zero, then I simply add “buzz” to the variable p. Bonus here is that p may already be equal to either blank or to “fizz” depending on the result of the previous test. The challenge states that if the integer is a multiple of both three and five, write “fizzbuzz”. This accomplishes this by either appending “buzz” to “fizz” if they are both multiples, or simply setting p to “buzz” if only five is a multiple of the integer.
- Finally, if p is still equal to blank after these prior tests, just set it to the value of the integer.
- Last, write p to the page along with a “<br />” linebreak in html to bump the output down a line and make the whole thing a little more human readable.
Where I went wrong:
- In my first implementation, i, the counter, was instantiated at 0 (zero), which is outside the bounds of the program guideline (and was a false-positive to both my modulus tests). That generated a false positive “fizzbuzz” as the first result AND set the entire set of results off by one integer. I could have also solved this by using another variable in the code that was set to i+1 each time through the loop, but that seemed redundant and a waste compared to instantiating i at 1 instead of 0.
- Second, I counted only up to 100, which left off the last integer to test, 100 itself, since I was starting at 1, not zero. I changed this by looping through until i<101. I could have also solved this by editing this part of the for loop to i<=100.
So, lets see your code!??
Latest posts by Robert Merrill (see all)
- Finding your Purpose in Work - August 10, 2014
- 5 Rules of Networking Relationships - July 10, 2014
- I’m Proud To Be American (But Not Arrogant About It) - July 4, 2014
- In Case of Emergency…. Walk Directly Into Fire - June 19, 2014