Skip to content

Instantly share code, notes, and snippets.

@io-developer
Created August 15, 2019 12:37
Show Gist options
  • Save io-developer/0d20527dc5e2f805d8fc38522780df19 to your computer and use it in GitHub Desktop.
Save io-developer/0d20527dc5e2f805d8fc38522780df19 to your computer and use it in GitHub Desktop.
<?php
function permute($items) {
$permutes = [];
permute_pairs($items, [], $permutes);
return $permutes;
}
function permute_pairs($items, $parents = [], &$out = []) {
for ($i = 0, $l = count($items); $i < $l; $i++) {
$base = $items[$i];
$subParents = $parents;
$subParents[] = $base;
if (count($items) === 1) {
$out[] = $subParents;
} else {
$rest = $items;
array_splice($rest, $i, 1);
permute_pairs($rest, $subParents, $out);
}
}
}
var_dump([
permute(['a', 'b', 'c', 'd']),
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment