I include these examples purely for instructional purposes. Generally the subject is given 10 minutes to complete each task.
Please note that if you are ever interviewing with me and you use these for your code examples, I’ll know.
For the numbers from 1 to 100:
I offer the following as a good example of how to do this. What I find astounding, is that about 40% of so-called programmers cannot execute this task.
My example not only solves the request, but allows for enhancement capability.
/**
* Computes the fizzbuzz for the specified range and returns the text
*
* @param $max how many terms to return
* @param $tests an array of additional values to check
* @return a string of comma separated terms
*/
function fizzBuzz($max=100, $tests=array()) {
// nomalize maximum value
$max = $max + 0;
if ($max < 1) $max = 100;
// set up test values
$defaultTests = array('Fizz' => 3, 'Buzz' => 5);
$tests = array_merge($defaultTests, $tests);
$results = '';
for ($i = 1; $i <= $max; $i++) {
$result = '';
foreach ($tests as $label => $modulo) if ($i % $modulo == 0) $result .= $label;
if (!$result) $result = $i;
$results .= $result;
if ($i == $max) {
$results .= "\n";
} else {
$results .= ', ';
}
}
return $results."\n";
}
echo '
FizzBuzz: an exercise in silly logic
';
echo fizzBuzz(123, array('Baz' => 47));
This example includes the additional test for multiples of 47
FizzBuzz: an exercise in silly logic
1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz, 16, 17, Fizz, 19, Buzz, Fizz, 22, 23, Fizz, Buzz, 26, Fizz, 28, 29, FizzBuzz, 31, 32, Fizz, 34, Buzz, Fizz, 37, 38, Fizz, Buzz, 41, Fizz, 43, 44, FizzBuzz, 46, Baz, Fizz, 49, Buzz, Fizz, 52, 53, Fizz, Buzz, 56, Fizz, 58, 59, FizzBuzz, 61, 62, Fizz, 64, Buzz, Fizz, 67, 68, Fizz, Buzz, 71, Fizz, 73, 74, FizzBuzz, 76, 77, Fizz, 79, Buzz, Fizz, 82, 83, Fizz, Buzz, 86, Fizz, 88, 89, FizzBuzz, 91, 92, Fizz, Baz, Buzz, Fizz, 97, 98, Fizz, Buzz, 101, Fizz, 103, 104, FizzBuzz, 106, 107, Fizz, 109, Buzz, Fizz, 112, 113, Fizz, Buzz, 116, Fizz, 118, 119, FizzBuzz, 121, 122, Fizz
Before we move on, one more example.
while($n++<100)echo$n%3?!$$n=$n:Fizz,$n%5?$$n:Buzz,"\n";1
2
Fatal error: Uncaught Error: Undefined constant "Fizz" in /home/abentley/www/pages/pgm101/final.html(75) : eval()'d code:1
Stack trace:
#0 /home/abentley/www/pages/pgm101/final.html(75): eval()
#1 /home/abentley/_framework/library/framework.php(128): include('...')
#2 /home/abentley/_framework/library/framework.php(62): FRAMEWORK::include_file()
#3 /home/abentley/_framework/library/framework.php(1473): FRAMEWORK::respond()
#4 /home/abentley/public_html/index.php(4): include_once('...')
#5 {main}
thrown in /home/abentley/www/pages/pgm101/final.html(75) : eval()'d code on line 1