Simplify combineWithRepetitions function.

This commit is contained in:
Oleksii Trekhleb 2018-06-28 14:05:58 +03:00
parent e5a06e654b
commit 65f08db5de
2 changed files with 24 additions and 31 deletions

View File

@ -1,38 +1,30 @@
/**
* @param {*[]} combinationOptions
* @param {number} combinationLength
* @param {*[]} comboOptions
* @param {number} comboLength
* @return {*[]}
*/
export default function combineWithRepetitions(combinationOptions, combinationLength) {
// If combination length equal to 0 then return empty combination.
if (combinationLength === 0) {
return [[]];
}
// If combination options are empty then return "no-combinations" array.
if (combinationOptions.length === 0) {
return [];
export default function combineWithRepetitions(comboOptions, comboLength) {
if (comboLength === 1) {
return comboOptions.map(comboOption => [comboOption]);
}
// Init combinations array.
const combos = [];
// Find all shorter combinations and attach head to each of those.
const headCombo = [combinationOptions[0]];
const shorterCombos = combineWithRepetitions(combinationOptions, combinationLength - 1);
// Eliminate characters one by one and concatenate them to
// combinations of smaller lengths.
for (let optionIndex = 0; optionIndex < comboOptions.length; optionIndex += 1) {
const currentOption = comboOptions[optionIndex];
for (let combinationIndex = 0; combinationIndex < shorterCombos.length; combinationIndex += 1) {
const combo = headCombo.concat(shorterCombos[combinationIndex]);
combos.push(combo);
}
// Let's shift head to the right and calculate all the rest combinations.
const combinationsWithoutHead = combineWithRepetitions(
combinationOptions.slice(1),
combinationLength,
const smallerCombos = combineWithRepetitions(
comboOptions.slice(optionIndex),
comboLength - 1,
);
// Join all combinations and return them.
return combos.concat(combinationsWithoutHead);
smallerCombos.forEach((smallerCombo) => {
combos.push([currentOption].concat(smallerCombo));
});
}
return combos;
}

View File

@ -8,20 +8,21 @@ export default function combineWithoutRepetitions(comboOptions, comboLength) {
return comboOptions.map(comboOption => [comboOption]);
}
// Init combinations array.
const combos = [];
// 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];
// combinations of smaller lengths.
for (let optionIndex = 0; optionIndex <= (comboOptions.length - comboLength); optionIndex += 1) {
const currentOption = comboOptions[optionIndex];
const smallerCombos = combineWithoutRepetitions(
comboOptions.slice(letterIndex + 1),
comboOptions.slice(optionIndex + 1),
comboLength - 1,
);
smallerCombos.forEach((smallerCombo) => {
combos.push([currentLetter].concat(smallerCombo));
combos.push([currentOption].concat(smallerCombo));
});
}