Last active
November 16, 2016 13:42
-
-
Save maxpou/e6cad8d4699f731c86df628358cba3d6 to your computer and use it in GitHub Desktop.
Some Fizzbuzz implementations
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// https://en.wikipedia.org/wiki/Fizz_buzz | |
// http://wiki.c2.com/?FizzBuzzTest | |
for ($i=0; $i < 200; $i++) { | |
echo printFizzzBuzz($i) . PHP_EOL; | |
echo printFizzzBuzzFunctionnal($i) . PHP_EOL; | |
echo printFizzzBuzzTernary($i) . PHP_EOL; | |
} | |
// ------------------- | |
// String concat way | |
// ------------------- | |
function printFizzzBuzz($value) | |
{ | |
$result = ''; | |
if ($value % 3 === 0) { | |
$result .= 'Fizz'; | |
} | |
if ($value % 5 === 0) { | |
$result .= 'Buzz'; | |
} | |
if (empty($result)) { | |
$result = $value; | |
} | |
return $result; | |
} | |
// -------- | |
// FP way | |
// -------- | |
function printFizzzBuzzFunctionnal($value) | |
{ | |
if ($value % 15 === 0) { | |
return 'FizzBuzz'; | |
} | |
if ($value % 3 === 0) { | |
return 'Fizz'; | |
} | |
if ($value % 5 === 0) { | |
return 'Buzz'; | |
} | |
return $value; | |
} | |
// ------------- | |
// Ternary way | |
// ------------- | |
function printFizzzBuzzTernary($value) | |
{ | |
return ($value % 15 === 0) ? 'FizzBuzz' : | |
(($value % 3 === 0) ? 'Fizz' : | |
(($value % 5 === 0) ? 'Buzz' : $value)); | |
} | |
// --------------- | |
// Recursive way | |
// --------------- | |
function printFizzzBuzzRecursive(int $start, int $end) | |
{ | |
if ($start % 15 === 0) { | |
echo 'FizzBuzz'; | |
} elseif ($start % 3 === 0) { | |
echo 'Fizz'; | |
} elseif ($start % 5 === 0) { | |
echo 'Buzz'; | |
} else { | |
echo $start; | |
} | |
echo PHP_EOL; | |
if ($start < $end) { | |
return printFizzzBuzzRecursive($start+1, $end); | |
} | |
} | |
printFizzzBuzzRecursive(1, 200); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment