Created
May 7, 2015 04:11
-
-
Save johnkary/dfcf766973d8917265c4 to your computer and use it in GitHub Desktop.
Kansas City PHP User Group - May 6, 2015 - FizzBuzz without PHP keywords if, else, for, foreach, do, while, switch, and ternary operator.
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 | |
$range = range(1,100); | |
$numbers = array_filter($range, function ($num) { | |
return $num % 3 !== 0 && $num % 5 !== 0; | |
}); | |
$fizz = array_filter($range, function ($num) { | |
return $num % 3 === 0 && $num % 5 !== 0; | |
}); | |
$buzz = array_filter($range, function ($num) { | |
return $num % 5 === 0 && $num % 3 !== 0; | |
}); | |
// [15, 30, 45, 60, ...] | |
$fizzbuzz = array_filter($range, function ($num) { | |
return $num % 5 === 0 && $num % 3 === 0; | |
}); | |
// [3, 6, 9, ...] | |
$numbers = array_combine($numbers, $numbers); | |
$fizz = to_output($fizz, 'Fizz'); | |
$buzz = to_output($buzz, 'Buzz'); | |
$fizzbuzz = to_output($fizzbuzz, 'FizzBuzz'); | |
// [1 => 1, 2 => 2, ...] | |
// [3 => 'Fizz', 6 => 'Fizz', ...] | |
// Sort into list of all values | |
$all = $numbers + $fizz + $buzz + $fizzbuzz; | |
// Order by array keys | |
ksort($all); | |
// Print all! | |
array_map(function ($num) { | |
echo "$num\n"; | |
}, $all); | |
/** | |
* Build list of numbers with their printed equivilant | |
*/ | |
function to_output(array $nums, $text) { | |
$fizzText = array_map(function () use ($text) { | |
return $text; | |
}, $nums); | |
return array_combine($nums, $fizzText); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment