|
1 | | -const permutations = function ( |
2 | | - original, |
3 | | - partialPermutations = original.map((num) => [num]), |
4 | | -) { |
5 | | - if (original.length <= 1) return [original]; |
| 1 | +const permutations = function (array, index = 0, results = []) { |
| 2 | + if (index == array.length) { |
| 3 | + // We have formed a valid permutation. |
6 | 4 |
|
7 | | - const newPartialPermutations = []; |
8 | | - partialPermutations.forEach((partialPermutation) => { |
9 | | - const missingNums = original.filter( |
10 | | - (num) => !partialPermutation.includes(num), |
11 | | - ); |
12 | | - missingNums.forEach((missingNum) => |
13 | | - newPartialPermutations.push([...partialPermutation, missingNum]), |
14 | | - ); |
15 | | - }); |
16 | | - |
17 | | - // We can pick any valid index because all of the elements will be the same length |
18 | | - const ANY_INDEX = 0; |
| 5 | + // the [...array] syntax is a way to clone the contents of the array. |
| 6 | + // because we do not want to pass a reference to the array, as that would mean |
| 7 | + // that each item in `results` will be the same item |
| 8 | + results.push([...array]); |
| 9 | + return results; |
| 10 | + } |
19 | 11 |
|
20 | | - if (newPartialPermutations[ANY_INDEX].length === original.length) { |
21 | | - return newPartialPermutations; |
| 12 | + for (let i = index; i < array.length; i++) { |
| 13 | + // We use "destructuring assignment" here to swap the values of array[index] and array[i] |
| 14 | + // |
| 15 | + // More info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment |
| 16 | + [array[index], array[i]] = [array[i], array[index]]; |
| 17 | + permutations(array, index + 1, results); |
| 18 | + [array[index], array[i]] = [array[i], array[index]]; |
22 | 19 | } |
23 | 20 |
|
24 | | - return permutations(original, newPartialPermutations); |
| 21 | + return results; |
25 | 22 | }; |
26 | 23 |
|
27 | 24 | // Do not edit below this line |
|
0 commit comments