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 {*[]} comboOptions
* @param {number} comboLength * @param {number} comboLength
* @param {*[][]} combos
* @param {*[]} currentCombo
* @return {*[]} * @return {*[]}
*/ */
function combineRecursively(comboOptions, comboLength, combos = [], currentCombo = []) { export default function combineWithoutRepetitions(comboOptions, comboLength) {
if (comboLength === 0) { if (comboLength === 1) {
combos.push(currentCombo); return comboOptions.map(comboOption => [comboOption]);
return combos;
} }
for (let letterIndex = 0; letterIndex <= (comboOptions.length - comboLength); letterIndex += 1) { const combos = [];
const letter = comboOptions[letterIndex];
const restCombinationOptions = comboOptions.slice(letterIndex + 1);
combineRecursively( // Eliminate characters one by one and concatenate them to
restCombinationOptions, // 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, comboLength - 1,
combos,
currentCombo.concat([letter]),
); );
smallerCombos.forEach((smallerCombo) => {
combos.push([currentLetter].concat(smallerCombo));
});
} }
return combos; return combos;
} }
/**
* @param {*[]} combinationOptions
* @param {number} combinationLength
* @return {*[]}
*/
export default function combineWithoutRepetitions(combinationOptions, combinationLength) {
return combineRecursively(combinationOptions, combinationLength);
}