The FizzBuzz Test

While reading Jeff Atwood’s blogpost entitled Why Can’t Programmers Program? I thought of testing whether I can pass the simple FizzBuzz test for programming he mentions. You can read the details of the test on his blogpost.

So I wrote a script in PHP, the language I am currently active in, to do what the test asks us to do.

But then, why stop at just solving the problem when you can optimize code for timepass?

I began with a 24 line-long (without counting empty lines) chunk of indented code, using a simple for loop and a bunch of if statements. But then I wanted to reduce the size of the code, so I decided to use the shorthand for if, and get rid of variable assignments that don’t “do” anything really. Now I am down to 5 lines of code, including the two lines of the for loop.

Turns out I am a programmer (though not formally educated as a programmer), and a good one at that – I passed the FizzBuzz Test!! 🙂 Do I get a job as a programmer now? 😛

Here is the output of the script (yes, the script ran when you loaded this page):

[php]
for ($j = 1; $j<=100; $j++) {
$fizz = ( $j % 3 == 0 ? 1 : 0 );
$buzz = ( $j % 5 == 0 ? 1 : 0 );
echo ($fizz + $buzz == 0 ? “$j
” : ($fizz == 1 ? “Fizz” : “”).($buzz == 1 ? “Buzz” : “”).”
“);
}
[/php]