Skip to content

Instantly share code, notes, and snippets.

@yitsushi
Created May 24, 2016 12:06
Show Gist options
  • Save yitsushi/55fb3c7024bc90f879427ae2d5b51256 to your computer and use it in GitHub Desktop.
Save yitsushi/55fb3c7024bc90f879427ae2d5b51256 to your computer and use it in GitHub Desktop.
<?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);
}
@yitsushi
Copy link
Author

[         test_permutations_rob] Total Execution Time: 0.328834
[    test_permutations_yitsushi] Total Execution Time: 0.079049

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment