Skip to content

Instantly share code, notes, and snippets.

@drupol
Last active November 29, 2020 10:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drupol/e237c6a69439a433c3479a2860207cb7 to your computer and use it in GitHub Desktop.
Save drupol/e237c6a69439a433c3479a2860207cb7 to your computer and use it in GitHub Desktop.
Fibonacci / Memoization / Solution
<?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