diff --git a/src/algorithms/sets/combinations/combineWithoutRepetitions.js b/src/algorithms/sets/combinations/combineWithoutRepetitions.js index 15678ee8..a6f50ec0 100644 --- a/src/algorithms/sets/combinations/combineWithoutRepetitions.js +++ b/src/algorithms/sets/combinations/combineWithoutRepetitions.js @@ -1,37 +1,29 @@ /** * @param {*[]} comboOptions * @param {number} comboLength - * @param {*[][]} combos - * @param {*[]} currentCombo * @return {*[]} */ -function combineRecursively(comboOptions, comboLength, combos = [], currentCombo = []) { - if (comboLength === 0) { - combos.push(currentCombo); - - return combos; +export default function combineWithoutRepetitions(comboOptions, comboLength) { + if (comboLength === 1) { + return comboOptions.map(comboOption => [comboOption]); } - for (let letterIndex = 0; letterIndex <= (comboOptions.length - comboLength); letterIndex += 1) { - const letter = comboOptions[letterIndex]; - const restCombinationOptions = comboOptions.slice(letterIndex + 1); + const combos = []; - combineRecursively( - restCombinationOptions, + // Eliminate characters one by one and concatenate them to + // combinations of smaller lengths.s + for (let letterIndex = 0; letterIndex <= (comboOptions.length - comboLength); letterIndex += 1) { + const currentLetter = comboOptions[letterIndex]; + + const smallerCombos = combineWithoutRepetitions( + comboOptions.slice(letterIndex + 1), comboLength - 1, - combos, - currentCombo.concat([letter]), ); + + smallerCombos.forEach((smallerCombo) => { + combos.push([currentLetter].concat(smallerCombo)); + }); } return combos; } - -/** - * @param {*[]} combinationOptions - * @param {number} combinationLength - * @return {*[]} - */ -export default function combineWithoutRepetitions(combinationOptions, combinationLength) { - return combineRecursively(combinationOptions, combinationLength); -}