Skip to content

Commit 5e4f4e2

Browse files
committed
feat: simpler solution for permutations (credit @JoshDevHub)
1 parent 2f0b347 commit 5e4f4e2

File tree

1 file changed

+17
-20
lines changed

1 file changed

+17
-20
lines changed

16_permutations/solution/permutations-solution.js

Lines changed: 17 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,24 @@
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.
64

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+
}
1911

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]];
2219
}
2320

24-
return permutations(original, newPartialPermutations);
21+
return results;
2522
};
2623

2724
// Do not edit below this line

0 commit comments

Comments
 (0)