Saturday, March 28, 2009

Alternative Take on FizzBuzz

This just in, my first reader submission for my blog, courtesy of Ahren from [XDF]. It's his alternative and well refined take on the FizzBuzz solution and a good demonstration that there's more than one way to skin this cat!

_i = 1; // Start at 1

// Assuming initially _x is 1
// repeat until _x is less than or equal to 100
// incrememnt _x by 1 each iteration
// combined this will iterate 100 times.
for [{_x=1},{_x<=100},{_x=_x+1}] do
{
_iThree = (_i/3);
_iFive = (_i/5);

// Uses a switch instead of multiple if statements!
switch (true) do
{
case (((_iThree) == floor(_iThree)) and !((_iFive) == floor(_iFive))):
{
hint "Fizz";
};
case (((_iFive) == floor(_iFive))and !((_iThree) == floor(_iThree))):
{
hint "Buzz";
};
case (((_iThree) == floor(_iThree))and((_iFive) == floor(_iFive))):
{
hint "FizzBuzz";
};
default
{
// Alternative to hint str(_i)
// Additionally you could use format to concatenate (link or add) two strings together
// e.g. hint format ["%1%2",_i," is not a multiple of 3 or 5"];
// if _i == 2 the following would be the hint:
// 2 is not a multiple of 3 or 5
hint format ["%1",_i];
};
};
_i = _i + 1;
sleep 0.5;
};

It should be pretty self explanatory, I thought of this after I posted the original solution and he beat me to implementing it, so we were obviously on the same track. Cheers Azza!

Also, I've added a few comments in to better explain a few things I skipped in the first solution, like a brief explanation on what "for" is, as well as a brief run down on the most common use of the format command with strings.

Jamie.

No comments:

Post a Comment