Created
October 1, 2017 18:07
-
-
Save lcherone/3a3b9273c9a798a33f57bb92d7b61434 to your computer and use it in GitHub Desktop.
Fibonacci sequence generator class, a play with PHP7 features.
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 | |
declare(strict_types=1); | |
/** | |
* Fibonacci sequence generator, a play with PHP7 features. | |
* @author Lawrence Cherone <cherone.co.uk> | |
*/ | |
class Fibonacci { | |
private $sequence = []; | |
/** | |
* Run/build sequence | |
* | |
* @param int $start - Starting number in sequence | |
* @param int $length - Length of sequence | |
* @return array | |
*/ | |
public function run (int $start, int $length = 10): array | |
{ | |
$this->sequence = [ | |
0, $start | |
]; | |
try { | |
for ($i=2; $i < $length; $i++) { | |
$this->sequence[$i] = $this->next( | |
$this->sequence[$i-2], | |
$this->sequence[$i-1] | |
); | |
} | |
} catch (\Exception $e) { | |
} | |
return $this->sequence; | |
} | |
/** | |
* Determine next number in sequence | |
* | |
* @param [int [, int]] Previous, Current ints in sequence | |
* @return int | |
*/ | |
public function next (int ...$seq): int | |
{ | |
$next = 0; | |
$next += \end($seq); | |
$next += \prev($seq); | |
if ($next > PHP_INT_MAX) { | |
throw new \Exception('Max limit reached'); | |
} | |
return $next; | |
} | |
/** | |
* The sum of all sequence | |
* | |
* @return mixed | |
*/ | |
public function sum () | |
{ | |
return \array_sum($this->sequence); | |
} | |
/** | |
* Sequence as string | |
* | |
* @return string | |
*/ | |
public function __toString(): string | |
{ | |
return \implode('-', $this->sequence); | |
} | |
} | |
$fibonacci = new \Fibonacci(); | |
$fibonacci->run(1, 25); | |
// 0-1-1-2-3-5-8-13-21-34-55-89-144-233-377-610-987-1597-2584-4181-6765-10946-17711-28657-46368 | |
echo $fibonacci; | |
// 121392 | |
echo $fibonacci->sum(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment