forked from trekhleb/javascript-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpermutateWithoutRepetitions.js
39 lines (32 loc) · 1.28 KB
/
permutateWithoutRepetitions.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
* @param {*[]} permutationOptions
* @return {*[]}
*/
export default function permutateWithoutRepetitions(permutationOptions) {
if (permutationOptions.length === 0) {
return [];
}
if (permutationOptions.length === 1) {
return [permutationOptions];
}
const permutations = [];
// Get all permutations of length (n - 1).
const previousOptions = permutationOptions.slice(0, permutationOptions.length - 1);
const previousPermutations = permutateWithoutRepetitions(previousOptions);
// Insert last option into every possible position of every previous permutation.
const lastOption = permutationOptions.slice(permutationOptions.length - 1);
for (
let permutationIndex = 0;
permutationIndex < previousPermutations.length;
permutationIndex += 1
) {
const currentPermutation = previousPermutations[permutationIndex];
// Insert last option into every possible position of currentPermutation.
for (let positionIndex = 0; positionIndex <= currentPermutation.length; positionIndex += 1) {
const permutationPrefix = currentPermutation.slice(0, positionIndex);
const permutationSuffix = currentPermutation.slice(positionIndex);
permutations.push(permutationPrefix.concat(lastOption, permutationSuffix));
}
}
return permutations;
}