Last active
March 31, 2016 03:36
-
-
Save sword-jin/0aea9cff96e5d1d5d1ebe87fbd3833c0 to your computer and use it in GitHub Desktop.
Get all permutations.
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 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; | |
| } | |
| } |
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
| #!/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