diff --git a/src/algorithms/sets/combinations/combineWithRepetitions.js b/src/algorithms/sets/combinations/combineWithRepetitions.js index 8a743289..0c3df4ec 100644 --- a/src/algorithms/sets/combinations/combineWithRepetitions.js +++ b/src/algorithms/sets/combinations/combineWithRepetitions.js @@ -4,6 +4,8 @@ * @return {*[]} */ export default function combineWithRepetitions(comboOptions, comboLength) { + // If the length of the combination is 1 then each element of the original array + // is a combination itself. if (comboLength === 1) { return comboOptions.map(comboOption => [comboOption]); } @@ -11,14 +13,16 @@ export default function combineWithRepetitions(comboOptions, comboLength) { // Init combinations array. const combos = []; - // Eliminate characters one by one and concatenate them to - // combinations of smaller lengths. + // Remember characters one by one and concatenate them to combinations of smaller lengths. + // We don't extract elements here because the repetitions are allowed. comboOptions.forEach((currentOption, optionIndex) => { + // Generate combinations of smaller size. const smallerCombos = combineWithRepetitions( comboOptions.slice(optionIndex), comboLength - 1, ); + // Concatenate currentOption with all combinations of smaller size. smallerCombos.forEach((smallerCombo) => { combos.push([currentOption].concat(smallerCombo)); }); diff --git a/src/algorithms/sets/combinations/combineWithoutRepetitions.js b/src/algorithms/sets/combinations/combineWithoutRepetitions.js index 56c1e8fe..ef08b8b6 100644 --- a/src/algorithms/sets/combinations/combineWithoutRepetitions.js +++ b/src/algorithms/sets/combinations/combineWithoutRepetitions.js @@ -4,6 +4,8 @@ * @return {*[]} */ export default function combineWithoutRepetitions(comboOptions, comboLength) { + // If the length of the combination is 1 then each element of the original array + // is a combination itself. if (comboLength === 1) { return comboOptions.map(comboOption => [comboOption]); } @@ -11,14 +13,16 @@ export default function combineWithoutRepetitions(comboOptions, comboLength) { // Init combinations array. const combos = []; - // Eliminate characters one by one and concatenate them to - // combinations of smaller lengths. + // Extract characters one by one and concatenate them to combinations of smaller lengths. + // We need to extract them because we don't want to have repetitions after concatenation. comboOptions.forEach((currentOption, optionIndex) => { + // Generate combinations of smaller size. const smallerCombos = combineWithoutRepetitions( comboOptions.slice(optionIndex + 1), comboLength - 1, ); + // Concatenate currentOption with all combinations of smaller size. smallerCombos.forEach((smallerCombo) => { combos.push([currentOption].concat(smallerCombo)); });