|
1 | | -/* |
2 | | -@see: https://stackoverflow.com/a/127898/7794070 |
3 | | -
|
4 | | - Lets say your array of letters looks like this: "ABCDEFGH". |
5 | | - You have three indices (i, j, k) indicating which letters you |
6 | | - are going to use for the current word, You start with: |
7 | | -
|
8 | | - A B C D E F G H |
9 | | - ^ ^ ^ |
10 | | - i j k |
11 | | -
|
12 | | - First you vary k, so the next step looks like that: |
13 | | -
|
14 | | - A B C D E F G H |
15 | | - ^ ^ ^ |
16 | | - i j k |
17 | | -
|
18 | | - If you reached the end you go on and vary j and then k again. |
19 | | -
|
20 | | - A B C D E F G H |
21 | | - ^ ^ ^ |
22 | | - i j k |
| 1 | +/** |
| 2 | + * @param{*[]} comboOptions |
| 3 | + * @param{number} comboLength |
| 4 | + * @param{*[][]} combos |
| 5 | + * @param{*[]} currentCombo |
| 6 | + * @return{*[]} |
| 7 | + */ |
| 8 | +functioncombineRecursively(comboOptions,comboLength,combos=[],currentCombo=[]){ |
| 9 | +if(comboLength===0){ |
| 10 | +combos.push(currentCombo); |
23 | 11 |
|
24 | | - A B C D E F G H |
25 | | - ^ ^ ^ |
26 | | - i j k |
| 12 | +returncombos; |
| 13 | +} |
27 | 14 |
|
28 | | - Once you j reached G you start also to vary i. |
| 15 | +for(letletterIndex=0;letterIndex<=(comboOptions.length-comboLength);letterIndex+=1){ |
| 16 | +constletter=comboOptions[letterIndex]; |
| 17 | +constrestCombinationOptions=comboOptions.slice(letterIndex+1); |
29 | 18 |
|
30 | | - A B C D E F G H |
31 | | - ^ ^ ^ |
32 | | - i j k |
| 19 | +combineRecursively( |
| 20 | +restCombinationOptions, |
| 21 | +comboLength-1, |
| 22 | +combos, |
| 23 | +currentCombo.concat([letter]), |
| 24 | +); |
| 25 | +} |
33 | 26 |
|
34 | | - A B C D E F G H |
35 | | - ^ ^ ^ |
36 | | - i j k |
37 | | - ... |
38 | | - */ |
| 27 | +returncombos; |
| 28 | +} |
39 | 29 |
|
40 | 30 | /** |
41 | 31 | * @param{*[]} combinationOptions |
42 | 32 | * @param{number} combinationLength |
43 | 33 | * @return{*[]} |
44 | 34 | */ |
45 | 35 | exportdefaultfunctioncombineWithoutRepetitions(combinationOptions,combinationLength){ |
46 | | -// If combination length is just 1 then return combinationOptions. |
47 | | -if(combinationLength===1){ |
48 | | -returncombinationOptions.map(option=>[option]); |
49 | | -} |
50 | | - |
51 | | -// Init combinations array. |
52 | | -constcombinations=[]; |
53 | | - |
54 | | -for(leti=0;i<=(combinationOptions.length-combinationLength);i+=1){ |
55 | | -constsmallerCombinations=combineWithoutRepetitions( |
56 | | -combinationOptions.slice(i+1), |
57 | | -combinationLength-1, |
58 | | -); |
59 | | - |
60 | | -for(letj=0;j<smallerCombinations.length;j+=1){ |
61 | | -constcombination=[combinationOptions[i]].concat(smallerCombinations[j]); |
62 | | -combinations.push(combination); |
63 | | -} |
64 | | -} |
65 | | - |
66 | | -// Return all calculated combinations. |
67 | | -returncombinations; |
| 36 | +returncombineRecursively(combinationOptions,combinationLength); |
68 | 37 | } |
0 commit comments