Created
March 10, 2015 14:53
-
-
Save chanmix51/3f4ee996572b6b398a1e to your computer and use it in GitHub Desktop.
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 | |
interface RuleInterface | |
{ | |
public function verify($i); | |
public function output($i); | |
} | |
class DefaultRule implements RuleInterface | |
{ | |
public function verify($i) | |
{ | |
return true; | |
} | |
public function output($i) | |
{ | |
return $i; | |
} | |
} | |
class FizzRule implements RuleInterface | |
{ | |
public function verify($i) | |
{ | |
return (bool) ($i % 3 === 0); | |
} | |
public function output($i) | |
{ | |
return 'fizz'; | |
} | |
} | |
class BuzzRule implements RuleInterface | |
{ | |
public function verify($i) | |
{ | |
return (bool) ($i % 5 === 0); | |
} | |
public function output($i) | |
{ | |
return 'buzz'; | |
} | |
} | |
class WhizzRule implements RuleInterface | |
{ | |
public function verify($i) | |
{ | |
return (bool) ($i % 7 === 0); | |
} | |
public function output($i) | |
{ | |
return 'whizz'; | |
} | |
} | |
class FizzBuzzRule implements RuleInterface | |
{ | |
public function verify($i) | |
{ | |
return (bool) ($i % 15 === 0); | |
} | |
public function output($i) | |
{ | |
return 'fizzbuzz'; | |
} | |
} | |
class FizzBuzz | |
{ | |
protected $rules = array(); | |
public function addRule(RuleInterface $rule) | |
{ | |
$this->rules[] = $rule; | |
return $this; | |
} | |
public function generate($n) | |
{ | |
$output = array(); | |
for ($i = 1; $i <= $n; $i++) { | |
$output[] = $i; | |
foreach ($this->rules as $j => $rule) { | |
if ($rule->verify($i)) { | |
$output[$i - 1] = $rule->output($i); | |
} | |
} | |
} | |
return $output; | |
} | |
} | |
$a = new FizzBuzz(); | |
$a | |
->addRule(new FizzRule()) | |
->addRule(new BuzzRule()) | |
->addRule(new WhizzRule()) | |
->addRule(new FizzBuzzRule()) | |
; | |
print_r($a->generate(15)); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment