This repository was archived by the owner on Dec 12, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathpermutateWithRepetitions.js
More file actions
42 lines (35 loc) · 1.38 KB
/
permutateWithRepetitions.js
File metadata and controls
42 lines (35 loc) · 1.38 KB
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
40
41
42
/**
* @param {*[]} permutationOptions
* @return {*[]}
*/
export default function permutateWithRepetitions(permutationOptions) {
// There is no permutations for empty array.
if (!permutationOptions || permutationOptions.length === 0) {
return [];
}
// There is only one permutation for the 1-element array.
if (permutationOptions.length === 1) {
return [permutationOptions];
}
// Let's create initial set of permutations.
let previousPermutations = permutationOptions.map(option => [option]);
let currentPermutations = [];
let permutationSize = 1;
// While the size of each permutation is less then or equal to options length...
while (permutationSize < permutationOptions.length) {
// Reset all current permutations.
currentPermutations = [];
for (let permIndex = 0; permIndex < previousPermutations.length; permIndex += 1) {
for (let optionIndex = 0; optionIndex < permutationOptions.length; optionIndex += 1) {
let currentPermutation = previousPermutations[permIndex];
currentPermutation = currentPermutation.concat([permutationOptions[optionIndex]]);
currentPermutations.push(currentPermutation);
}
}
// Make current permutations to be the previous ones.
previousPermutations = currentPermutations.slice(0);
// Increase permutation size counter.
permutationSize += 1;
}
return currentPermutations;
}