Last active
November 29, 2020 10:42
-
-
Save drupol/e237c6a69439a433c3479a2860207cb7 to your computer and use it in GitHub Desktop.
Fibonacci / Memoization / Solution
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); | |
namespace App; | |
use ArrayObject; | |
use Closure; | |
use Generator; | |
function memoize(Closure $closure, ?ArrayObject $cache = null): Closure | |
{ | |
$cache = $cache ?? new ArrayObject(); | |
return | |
/** | |
* @psalm-suppress MixedAssignment | |
* | |
* @param mixed ...$arguments | |
* | |
* @return mixed | |
*/ | |
static fn (...$arguments) => $cache[ | |
sha1(serialize(json_encode($arguments))) | |
] ??= ($closure)(...$arguments); | |
} | |
function bench(Closure $closure, ...$arguments): array | |
{ | |
$benchGenerator = static function (Closure $closure, ...$arguments): Generator | |
{ | |
yield microtime(true); | |
yield $closure(...$arguments); | |
yield microtime(true); | |
}; | |
$result = iterator_to_array($benchGenerator($closure, ...$arguments)); | |
return [ | |
$result[1], | |
$result[2] - $result[0], | |
]; | |
} | |
$fibonacci = static function (int $number) use (&$fibonacci): int { | |
return (1 >= $number) ? | |
$number: | |
$fibonacci($number - 1) + $fibonacci($number - 2); | |
}; | |
$sleep = static function (int $number): int | |
{ | |
sleep($number); | |
return $number; | |
}; | |
$fibonacci = memoize($fibonacci); | |
$sleep = memoize($sleep); | |
var_dump(sprintf('[return: %s] [duration: %s]', ...bench($fibonacci, 10))); | |
var_dump(sprintf('[return: %s] [duration: %s]', ...bench($fibonacci, 10))); | |
var_dump(sprintf('[return: %s] [duration: %s]', ...bench($sleep, 10))); | |
var_dump(sprintf('[return: %s] [duration: %s]', ...bench($sleep, 10))); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment