File tree Expand file tree Collapse file tree 2 files changed +12
-4
lines changed
src/algorithms/sets/combinations Expand file tree Collapse file tree 2 files changed +12
-4
lines changed Original file line number Diff line number Diff line change 44 * @return {*[] }
55 */
66export 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.
79 if ( comboLength === 1 ) {
810 return comboOptions . map ( comboOption => [ comboOption ] ) ;
911 }
1012
1113 // Init combinations array.
1214 const combos = [ ] ;
1315
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 .
1618 comboOptions . forEach ( ( currentOption , optionIndex ) => {
19+ // Generate combinations of smaller size.
1720 const smallerCombos = combineWithRepetitions (
1821 comboOptions . slice ( optionIndex ) ,
1922 comboLength - 1 ,
2023 ) ;
2124
25+ // Concatenate currentOption with all combinations of smaller size.
2226 smallerCombos . forEach ( ( smallerCombo ) => {
2327 combos . push ( [ currentOption ] . concat ( smallerCombo ) ) ;
2428 } ) ;
Original file line number Diff line number Diff line change 44 * @return {*[] }
55 */
66export 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.
79 if ( comboLength === 1 ) {
810 return comboOptions . map ( comboOption => [ comboOption ] ) ;
911 }
1012
1113 // Init combinations array.
1214 const combos = [ ] ;
1315
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 .
1618 comboOptions . forEach ( ( currentOption , optionIndex ) => {
19+ // Generate combinations of smaller size.
1720 const smallerCombos = combineWithoutRepetitions (
1821 comboOptions . slice ( optionIndex + 1 ) ,
1922 comboLength - 1 ,
2023 ) ;
2124
25+ // Concatenate currentOption with all combinations of smaller size.
2226 smallerCombos . forEach ( ( smallerCombo ) => {
2327 combos . push ( [ currentOption ] . concat ( smallerCombo ) ) ;
2428 } ) ;
You can’t perform that action at this time.
0 commit comments