Last active
December 30, 2015 04:19
-
-
Save bdelespierre/7775130 to your computer and use it in GitHub Desktop.
Fibonnaci numbers generator
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 | |
| // quick'n dirty | |
| class Fibonacci implements Iterator { | |
| public function __construct () { | |
| $this->rewind(); | |
| } | |
| public function __invoke () { | |
| $n = $this->current(); | |
| $this->next(); | |
| return $n; | |
| } | |
| public function current () { | |
| return $this->n; | |
| } | |
| public function key () { | |
| return $this->k; | |
| } | |
| public function next () { | |
| $this->k++; | |
| if ($this->k == 0) | |
| $this->n = 0; | |
| elseif ($this->k == 1) | |
| $this->n = 1; | |
| else { | |
| $this->n = $this->prev[0] + $this->prev[1]; | |
| $this->prev[0] = $this->prev[1]; | |
| $this->prev[1] = $this->n; | |
| } | |
| } | |
| public function rewind () { | |
| $this->n = 0; | |
| $this->k = 0; | |
| $this->prev = [0,1]; | |
| } | |
| public function valid () { | |
| return true; | |
| } | |
| } | |
| $fibonacci_generator = new Fibonacci; | |
| foreach (range(1,10) as $i) | |
| echo $fibonacci_generator() . "\n"; | |
| foreach (range(1,10) as $i) | |
| echo $fibonacci_generator() . "\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment