Created
August 24, 2020 20:53
-
-
Save neenjaw/df027d814ce25fea5f3d84951875e042 to your computer and use it in GitHub Desktop.
PHP fizzbuzz
This file contains 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 | |
// Approach 1 | |
$lb = "\n"; | |
for ($i = 1; $i <= 100; $i++) | |
{ | |
if ($i % 15 === 0) { | |
echo "FizzBuzz $lb"; | |
} | |
else if($i % 3 == 0){ | |
echo "Fizz $lb"; | |
} | |
else if($i % 5 == 0){ | |
echo "Buzz $lb"; | |
} | |
else { | |
echo $i." $lb"; | |
} | |
} | |
// Approach 2 | |
foreach (range(1, 100) as $number) { | |
echo fizzbuzz($number). "\n"; | |
} | |
function fizzbuzz(int $num): string | |
{ | |
$isFizz = $num % 3 == 0; | |
$isBuzz = $num % 5 == 0; | |
$fizzBuzz = ($isFizz ? 'fizz' : '') . ($isBuzz ? 'buzz' : ''); | |
return !empty($fizzBuzz) ? $fizzBuzz : (string) $num; | |
} | |
// Approach 3 | |
function isFactor(int $n, int $divisor): bool | |
{ | |
return $n % $divisor === 0; | |
} | |
function fizzbuzz2(int $num, array $rules): string | |
{ | |
$words = array_map(fn($f) => $f($num), $rules); | |
$combined = join('', $words); | |
return !empty($combined) ? $combined : (string) $num; | |
} | |
$rules = [ | |
fn($n) => isFactor($n, 3) ? 'fizz' : '', | |
fn($n) => isFactor($n, 5) ? 'fizz' : '' | |
]; | |
foreach (range(1, 100) as $number) { | |
echo fizzbuzz2($number, $rules). "\n"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment