Simplify combineWithoutRepetitions function.

This commit is contained in:
Oleksii Trekhleb
2018-06-28 13:46:26 +03:00
parent 55ecc0b313
commit e5a06e654b

View File

@ -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);
}