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 pathcombineWithoutRepetitions.js
More file actions
68 lines (53 loc) · 1.5 KB
/
combineWithoutRepetitions.js
File metadata and controls
68 lines (53 loc) · 1.5 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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/*
@see: https://stackoverflow.com/a/127898/7794070
Lets say your array of letters looks like this: "ABCDEFGH".
You have three indices (i, j, k) indicating which letters you
are going to use for the current word, You start with:
A B C D E F G H
^ ^ ^
i j k
First you vary k, so the next step looks like that:
A B C D E F G H
^ ^ ^
i j k
If you reached the end you go on and vary j and then k again.
A B C D E F G H
^ ^ ^
i j k
A B C D E F G H
^ ^ ^
i j k
Once you j reached G you start also to vary i.
A B C D E F G H
^ ^ ^
i j k
A B C D E F G H
^ ^ ^
i j k
...
*/
/**
* @param {*[]} combinationOptions
* @param {number} combinationLength
* @return {*[]}
*/
export default function combineWithoutRepetitions(combinationOptions, combinationLength) {
// If combination length is just 1 then return combinationOptions.
if (combinationLength === 1) {
return combinationOptions.map(option => [option]);
}
// Init combinations array.
const combinations = [];
for (let i = 0; i <= (combinationOptions.length - combinationLength); i += 1) {
const smallerCombinations = combineWithoutRepetitions(
combinationOptions.slice(i + 1),
combinationLength - 1,
);
for (let j = 0; j < smallerCombinations.length; j += 1) {
const combination = [combinationOptions[i]].concat(smallerCombinations[j]);
combinations.push(combination);
}
}
// Return all calculated combinations.
return combinations;
}