Created
May 24, 2016 12:06
-
-
Save yitsushi/55fb3c7024bc90f879427ae2d5b51256 to your computer and use it in GitHub Desktop.
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 | |
function test_permutations_rob($items, $perms = [], &$return = []) { | |
if (empty($items)) { | |
$return[] = $perms; | |
} else { | |
sort($items); | |
$prev = false; | |
for ($i = count($items) - 1; $i >= 0; --$i) { | |
$newitems = $items; | |
$tmp = array_splice($newitems, $i, 1)[0]; | |
if ($tmp != $prev) { | |
$prev = $tmp; | |
$newperms = $perms; | |
array_unshift($newperms, $tmp); | |
test_permutations_rob($newitems, $newperms, $return); | |
} | |
} | |
return $return; | |
} | |
} | |
function test_permutations_yitsushi(array $stack) { | |
if (count($stack) < 2) { | |
yield $stack; | |
} else { | |
foreach (test_permutations_yitsushi(array_slice($stack, 1)) as $iteration) { | |
foreach (range(0, count($stack) - 1) as $i) { | |
yield array_merge( | |
array_slice($iteration, 0, $i), | |
[$stack[0]], | |
array_slice($iteration, $i) | |
); | |
} | |
} | |
} | |
} | |
function executePermutationWithTimer(callable $function) { | |
$base_array = [1, 2, 3, 4, 5, 6, 7, 8]; | |
$start = microtime(true); | |
foreach($function($base_array) as $item) {} | |
$end = microtime(true); | |
printf("[%30s] Total Execution Time: %f\n", $function, ($end - $start)); | |
} | |
$functions = array_filter( | |
get_defined_functions()['user'], | |
function($item) { | |
return substr_compare($item, 'test_', 0, 4) == 0; | |
} | |
); | |
foreach($functions as $f) { | |
executePermutationWithTimer($f); | |
} |
Author
yitsushi
commented
May 24, 2016
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment