Last active
March 7, 2018 00:56
-
-
Save mtdowling/4516558 to your computer and use it in GitHub Desktop.
Fibonacci in PHP using anonymous functions and memoization
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 | |
$fibMemo = call_user_func(function () { | |
$memo = array(0 => 0, 1 => 1); | |
$fib = function ($n) use (&$memo, &$fib) { | |
if (!isset($memo[$n])) { | |
$memo[$n] = $fib($n - 1) + $fib($n - 2); | |
} | |
return $memo[$n]; | |
}; | |
return $fib; | |
}); | |
echo $fibMemo(10); | |
// >> 55 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Awesome!!, it does work, but when does it stop?? Shouldn't be a condition (n<2) return n???, if you put a echo inside the anonymous function you could see that it is doing a doble loop...