Skip to content

Instantly share code, notes, and snippets.

@sword-jin
Last active March 31, 2016 03:36
Show Gist options
  • Select an option

  • Save sword-jin/0aea9cff96e5d1d5d1ebe87fbd3833c0 to your computer and use it in GitHub Desktop.

Select an option

Save sword-jin/0aea9cff96e5d1d5d1ebe87fbd3833c0 to your computer and use it in GitHub Desktop.
Get all permutations.
<?php
function permutations(array $array) {
if (count($array) == 0) {
return [];
} elseif (count($array) == 1) {
return $array;
} else {
$results = [];
for ($i = 0; $i < count($array); $i ++) {
$x = $array[$i];
$xs = array_merge(array_slice($array, 0, $i), array_slice($array, $i + 1));
foreach (permutations($xs) as $p) {
if (is_array($p)) {
$results[] = array_merge([$x], $p);
} else {
$results[] = array_merge([$x], [$p]);
}
}
}
return $results;
}
}
#!/usr/bin/env python
def perm(lst):
"""Just for list"""
if len(lst) == 0:
return []
elif len(lst) == 1:
return lst
else:
l = []
for i in range(len(lst)):
x = lst[i]
xs = lst[:i] + lst[i + 1:]
for p in perm(xs):
if isinstance(p, int):
l.append([x] + [p])
else:
l.append([x] + p)
return l
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment