forked from trekhleb/javascript-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcombineWithRepetitions.js
More file actions
38 lines (31 loc) · 1.16 KB
/
combineWithRepetitions.js
File metadata and controls
38 lines (31 loc) · 1.16 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
/**
* @param {*[]} combinationOptions
* @param {number} combinationLength
* @return {*[]}
*/
export default function combineWithRepetitions(combinationOptions, combinationLength) {
// If combination length equal to 0 then return empty combination.
if (combinationLength === 0) {
return [[]];
}
// If combination options are empty then return "no-combinations" array.
if (combinationOptions.length === 0) {
return [];
}
// Init combinations array.
const combos = [];
// Find all shorter combinations and attach head to each of those.
const headCombo = [combinationOptions[0]];
const shorterCombos = combineWithRepetitions(combinationOptions, combinationLength - 1);
for (let combinationIndex = 0; combinationIndex < shorterCombos.length; combinationIndex += 1) {
const combo = headCombo.concat(shorterCombos[combinationIndex]);
combos.push(combo);
}
// Let's shift head to the right and calculate all the rest combinations.
const combinationsWithoutHead = combineWithRepetitions(
combinationOptions.slice(1),
combinationLength,
);
// Join all combinations and return them.
return combos.concat(combinationsWithoutHead);
}