mirror of
https://github.com/trekhleb/javascript-algorithms.git
synced 2025-07-07 01:44:52 +08:00
Simplify combineWithoutRepetitions function.
This commit is contained in:
@ -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);
|
|
||||||
}
|
|
||||||
|
Reference in New Issue
Block a user