Tuesday 11 September 2018

Web Tutorial: The FizzBuzz Solution

Following my piece on FizzBuzz last month, I thought it would be fun (see what my idea of fun is? Man, I'm such a geek) to walk you through the painfully simple process of a FizzBuzz program. Of course, the program is simple enough - what's really important is understanding the process.

To make it even more fun, I'm going to do it in Ruby. Because... well, why not?

First, at the risk of sounding repetitive, let's look at the program specs again.
Write a program that prints the numbers from 1 to 100. But for multiple 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".


So, it sounds like this requires some kind of For loop. But let's keep this small, say, 20 instead of 100.
for i in 1..20

end


By default, we print out the number.
for i in 1..20
    puts i
end


And here we are.


Now, this is hardly optimal. We are going to have some conditionals in between. So since the default is printing out the number, let's first create a variable, output, and assign the value of i to it. Then print out output. This will still give you the same output, but your code is more extensible now.
for i in 1..20
    output = i

    puts output
end


Here's the first condition. If the Modulus of i/3 is 0, which means that i is divisible by 3, the value of output is "Fizz".
for i in 1..20
    output = i

    if i % 3 == 0
        output = "Fizz"
    end

    puts output
end


Yep. Seems to be working!


And if i is divisible by 5, the value of output is "Buzz".
for i in 1..20
    output = i

    if i % 3 == 0
        output = "Fizz"
    end

    if i % 5 == 0
        output = "Buzz"
    end

    puts output
end


Getting closer...


Now for the grand slam! If i is divisible by both 3 and 5, the value of output is "FizzBuzz".
for i in 1..20
    output = i
   
    if i % 3 == 0
        output = "Fizz"
    end

    if i % 5 == 0
        output = "Buzz"
    end

    if (i % 3 == 0 and i % 5 == 0)
        output = "FizzBuzz"
    end

    puts output
end


Great. It works. Just one more thing...


Make the program loop 100 times instead of 20.
for i in 1..100
    output = i
   
    if i % 3 == 0
        output = "Fizz"
    end

    if i % 5 == 0
        output = "Buzz"
    end

    if (i % 3 == 0 and i % 5 == 0)
        output = "FizzBuzz"
    end

    puts output
end


Mission accomplished!


Final notes

Yes, it really was a simple piece of work. And does nothing useful at all.

As mentioned, FizzBuzz is really just a way to ensure that a programming candidate understands how to use loops, conditionals and the Modulus operator. We did it in Ruby, but it really could have been done in any programming language.

puts "Bye!"
T___T

No comments:

Post a Comment