Fizzbuzz with two if-statements

What’s fizzbuzz?

According to http://wiki.c2.com/?FizzBuzzTest

The “Fizz-Buzz test” is an interview question designed to help filter out the 99.5% of programming job candidates who can’t seem to program their way out of a wet paper bag. The text of the programming assignment is as follows:
“Write a program that prints the numbers from 1 to 100. But for multiples 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”.”

Everyone who knows to program a little bit can solve this problem.
However, there is something in there that makes the naive solution seem to be a bit ugly and I always wanted to find a way to overcome this. That is, to write the naive code, one would check for divisibility by 3 and divisibility by 5. To check divisibility by 15, one could use the flags obtained by the previous checks or make a new check for divisibility by 15.

Taking the pseudo code from http://wiki.c2.com/?FizzBuzzTest again, we would obtain something similar to this:

 
if (theNumber is divisible by 3) and (theNumber is divisible by 5) then
	print "FizzBuzz"
else if (theNumber is divisible by 3) then
	print "Fizz"
else if (theNumber is divisible by 5) then
	print "Buzz"
else /* theNumber is not divisible by 3 or 5 */
	print theNumber
end if

A matrix approach

The above code seems redundant because we make three checks but all information is contained within two checks, since divisibility by 3 and 5 implies divisibility by 15.
However, we can perform both checks and just do the printing afterwards and not immediately. With i indicating divisibility by 3 and j indicating divisibility by 5 we can access a matrix M. We just have to shift by one since Matlab is one-indexed and not starting arrays at zero. Since we are not printing numbers but strings, we use a cell array instead of a standard matrix. Three of the values in this cell array are fixed, i.e. fizz, buzz and fizzbuzz. The last entry is the string version of the number itself. We write that to the cell array at every loop iteration. The code then looks like this:

function fizzbuzz

M{1, 1} = '';       M{1, 2} = 'fizz';
M{2, 1} = 'buzz';   M{2, 2} = 'fizzbuzz';

for n = 1:100
    M{1, 1} = num2str(n); % put the current number in the slot (1,1)
    j = mod(n, 3) == 0;   % check divisibility by 3
    i = mod(n, 5) == 0;   % check divisibility by 5
    disp(M{i+1, j+1})     % print
end

Different ways

I am not the first person to consider this problem, obviously. You can find a question on StackOverflow that asks the exact same question. However, I could not manage to understand all the solutions provided, that’s why I came up with a more “math-like” way, i.e. the code above.

Leave a Reply