|
3 | 3 | * @return {*[]}
|
4 | 4 | */
|
5 | 5 | export default function permutateWithoutRepetitions(permutationOptions) {
|
6 |
| - if (permutationOptions.length === 0) { |
7 |
| - return []; |
8 |
| - } |
9 |
| - |
10 | 6 | if (permutationOptions.length === 1) {
|
11 | 7 | return [permutationOptions];
|
12 | 8 | }
|
13 | 9 |
|
| 10 | + // Init permutations array. |
14 | 11 | const permutations = [];
|
15 | 12 |
|
16 |
| - // Get all permutations of length (n - 1). |
17 |
| - const previousOptions = permutationOptions.slice(0, permutationOptions.length - 1); |
18 |
| - const previousPermutations = permutateWithoutRepetitions(previousOptions); |
| 13 | + // Get all permutations for permutationOptions excluding the first element. |
| 14 | + const smallerPermutations = permutateWithoutRepetitions(permutationOptions.slice(1)); |
19 | 15 |
|
20 |
| - // Insert last option into every possible position of every previous permutation. |
21 |
| - const lastOption = permutationOptions.slice(permutationOptions.length - 1); |
| 16 | + // Insert first option into every possible position of every smaller permutation. |
| 17 | + const firstOption = permutationOptions[0]; |
22 | 18 |
|
23 |
| - for ( |
24 |
| - let permutationIndex = 0; |
25 |
| - permutationIndex < previousPermutations.length; |
26 |
| - permutationIndex += 1 |
27 |
| - ) { |
28 |
| - const currentPermutation = previousPermutations[permutationIndex]; |
| 19 | + for (let permIndex = 0; permIndex < smallerPermutations.length; permIndex += 1) { |
| 20 | + const smallerPermutation = smallerPermutations[permIndex]; |
29 | 21 |
|
30 |
| - // Insert last option into every possible position of currentPermutation. |
31 |
| - for (let positionIndex = 0; positionIndex <= currentPermutation.length; positionIndex += 1) { |
32 |
| - const permutationPrefix = currentPermutation.slice(0, positionIndex); |
33 |
| - const permutationSuffix = currentPermutation.slice(positionIndex); |
34 |
| - permutations.push(permutationPrefix.concat(lastOption, permutationSuffix)); |
| 22 | + // Insert first option into every possible position of smallerPermutation. |
| 23 | + for (let positionIndex = 0; positionIndex <= smallerPermutation.length; positionIndex += 1) { |
| 24 | + const permutationPrefix = smallerPermutation.slice(0, positionIndex); |
| 25 | + const permutationSuffix = smallerPermutation.slice(positionIndex); |
| 26 | + permutations.push(permutationPrefix.concat([firstOption], permutationSuffix)); |
35 | 27 | }
|
36 | 28 | }
|
37 | 29 |
|
|
0 commit comments