|
1 | 1 | /** |
2 | 2 | * @param {*[]} comboOptions |
3 | 3 | * @param {number} comboLength |
4 | | - * @param {*[][]} combos |
5 | | - * @param {*[]} currentCombo |
6 | 4 | * @return {*[]} |
7 | 5 | */ |
8 | | -function combineRecursively(comboOptions, comboLength, combos = [], currentCombo = []) { |
9 | | - if (comboLength === 0) { |
10 | | - combos.push(currentCombo); |
11 | | - |
12 | | - return combos; |
| 6 | +export default function combineWithoutRepetitions(comboOptions, comboLength) { |
| 7 | + if (comboLength === 1) { |
| 8 | + return comboOptions.map(comboOption => [comboOption]); |
13 | 9 | } |
14 | 10 |
|
| 11 | + const combos = []; |
| 12 | + |
| 13 | + // Eliminate characters one by one and concatenate them to |
| 14 | + // combinations of smaller lengths.s |
15 | 15 | for (let letterIndex = 0; letterIndex <= (comboOptions.length - comboLength); letterIndex += 1) { |
16 | | - const letter = comboOptions[letterIndex]; |
17 | | - const restCombinationOptions = comboOptions.slice(letterIndex + 1); |
| 16 | + const currentLetter = comboOptions[letterIndex]; |
18 | 17 |
|
19 | | - combineRecursively( |
20 | | - restCombinationOptions, |
| 18 | + const smallerCombos = combineWithoutRepetitions( |
| 19 | + comboOptions.slice(letterIndex + 1), |
21 | 20 | comboLength - 1, |
22 | | - combos, |
23 | | - currentCombo.concat([letter]), |
24 | 21 | ); |
| 22 | + |
| 23 | + smallerCombos.forEach((smallerCombo) => { |
| 24 | + combos.push([currentLetter].concat(smallerCombo)); |
| 25 | + }); |
25 | 26 | } |
26 | 27 |
|
27 | 28 | return combos; |
28 | 29 | } |
29 | | - |
30 | | -/** |
31 | | - * @param {*[]} combinationOptions |
32 | | - * @param {number} combinationLength |
33 | | - * @return {*[]} |
34 | | - */ |
35 | | -export default function combineWithoutRepetitions(combinationOptions, combinationLength) { |
36 | | - return combineRecursively(combinationOptions, combinationLength); |
37 | | -} |
0 commit comments