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