Skip to content

Instantly share code, notes, and snippets.

@thedom85
Created July 13, 2022 08:31
Show Gist options
  • Save thedom85/f0c3a44716cad8950b78c48565be827a to your computer and use it in GitHub Desktop.
Save thedom85/f0c3a44716cad8950b78c48565be827a to your computer and use it in GitHub Desktop.
Math js example combination - combineWithRepetitions - combineWithoutRepetitions
/**
* @param {*[]} comboOptions
* @param {number} comboLength
* @return {*[]}
*/
function combineWithRepetitions(comboOptions, comboLength) {
// If the length of the combination is 1 then each element of the original array
// is a combination itself.
if (comboLength === 1) {
return comboOptions.map((comboOption) => [comboOption]);
}
// Init combinations array.
const combos = [];
// Remember characters one by one and concatenate them to combinations of smaller lengths.
// We don't extract elements here because the repetitions are allowed.
comboOptions.forEach((currentOption, optionIndex) => {
// Generate combinations of smaller size.
const smallerCombos = combineWithRepetitions(
comboOptions.slice(optionIndex),
comboLength - 1,
);
// Concatenate currentOption with all combinations of smaller size.
smallerCombos.forEach((smallerCombo) => {
combos.push([currentOption].concat(smallerCombo));
});
});
return combos;
}
console.log(combineWithRepetitions(['A', 'B', 'C'], 2),[
['A', 'A', 'A'],
['A', 'A', 'B'],
['A', 'A', 'C'],
['A', 'B', 'B'],
['A', 'B', 'C'],
['A', 'C', 'C'],
['B', 'B', 'B'],
['B', 'B', 'C'],
['B', 'C', 'C'],
['C', 'C', 'C'],
]);
/**
* @param {*[]} comboOptions
* @param {number} comboLength
* @return {*[]}
*/
function combineWithoutRepetitions(comboOptions, comboLength) {
// If the length of the combination is 1 then each element of the original array
// is a combination itself.
if (comboLength === 1) {
return comboOptions.map((comboOption) => [comboOption]);
}
// Init combinations array.
const combos = [];
// Extract characters one by one and concatenate them to combinations of smaller lengths.
// We need to extract them because we don't want to have repetitions after concatenation.
comboOptions.forEach((currentOption, optionIndex) => {
// Generate combinations of smaller size.
const smallerCombos = combineWithoutRepetitions(
comboOptions.slice(optionIndex + 1),
comboLength - 1,
);
// Concatenate currentOption with all combinations of smaller size.
smallerCombos.forEach((smallerCombo) => {
combos.push([currentOption].concat(smallerCombo));
});
});
return combos;
}
console.log(combineWithoutRepetitions(['A', 'B', 'C', 'D', 'E'], 3),[
['A', 'B', 'C'],
['A', 'B', 'D'],
['A', 'B', 'E'],
['A', 'C', 'D'],
['A', 'C', 'E'],
['A', 'D', 'E'],
['B', 'C', 'D'],
['B', 'C', 'E'],
['B', 'D', 'E'],
['C', 'D', 'E'],
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment