File tree 2 files changed +12
-4
lines changed
src/algorithms/sets/combinations
2 files changed +12
-4
lines changed Original file line number Diff line number Diff line change 4
4
* @return {*[] }
5
5
*/
6
6
export default function combineWithRepetitions ( comboOptions , comboLength ) {
7
+ // If the length of the combination is 1 then each element of the original array
8
+ // is a combination itself.
7
9
if ( comboLength === 1 ) {
8
10
return comboOptions . map ( comboOption => [ comboOption ] ) ;
9
11
}
10
12
11
13
// Init combinations array.
12
14
const combos = [ ] ;
13
15
14
- // Eliminate characters one by one and concatenate them to
15
- // combinations of smaller lengths .
16
+ // Remember characters one by one and concatenate them to combinations of smaller lengths.
17
+ // We don't extract elements here because the repetitions are allowed .
16
18
comboOptions . forEach ( ( currentOption , optionIndex ) => {
19
+ // Generate combinations of smaller size.
17
20
const smallerCombos = combineWithRepetitions (
18
21
comboOptions . slice ( optionIndex ) ,
19
22
comboLength - 1 ,
20
23
) ;
21
24
25
+ // Concatenate currentOption with all combinations of smaller size.
22
26
smallerCombos . forEach ( ( smallerCombo ) => {
23
27
combos . push ( [ currentOption ] . concat ( smallerCombo ) ) ;
24
28
} ) ;
Original file line number Diff line number Diff line change 4
4
* @return {*[] }
5
5
*/
6
6
export default function combineWithoutRepetitions ( comboOptions , comboLength ) {
7
+ // If the length of the combination is 1 then each element of the original array
8
+ // is a combination itself.
7
9
if ( comboLength === 1 ) {
8
10
return comboOptions . map ( comboOption => [ comboOption ] ) ;
9
11
}
10
12
11
13
// Init combinations array.
12
14
const combos = [ ] ;
13
15
14
- // Eliminate characters one by one and concatenate them to
15
- // combinations of smaller lengths .
16
+ // Extract characters one by one and concatenate them to combinations of smaller lengths.
17
+ // We need to extract them because we don't want to have repetitions after concatenation .
16
18
comboOptions . forEach ( ( currentOption , optionIndex ) => {
19
+ // Generate combinations of smaller size.
17
20
const smallerCombos = combineWithoutRepetitions (
18
21
comboOptions . slice ( optionIndex + 1 ) ,
19
22
comboLength - 1 ,
20
23
) ;
21
24
25
+ // Concatenate currentOption with all combinations of smaller size.
22
26
smallerCombos . forEach ( ( smallerCombo ) => {
23
27
combos . push ( [ currentOption ] . concat ( smallerCombo ) ) ;
24
28
} ) ;
You can’t perform that action at this time.
0 commit comments