mirror of
https://github.moeyy.xyz/https://github.com/trekhleb/javascript-algorithms.git
synced 2024-12-25 06:16:11 +08:00
Add comments to combination algorithms.
This commit is contained in:
parent
6261d0e9bb
commit
f08fc37dad
@ -4,6 +4,8 @@
|
||||
* @return {*[]}
|
||||
*/
|
||||
export default 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]);
|
||||
}
|
||||
@ -11,14 +13,16 @@ export default function combineWithRepetitions(comboOptions, comboLength) {
|
||||
// Init combinations array.
|
||||
const combos = [];
|
||||
|
||||
// Eliminate characters one by one and concatenate them to
|
||||
// combinations of smaller lengths.
|
||||
// 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));
|
||||
});
|
||||
|
@ -4,6 +4,8 @@
|
||||
* @return {*[]}
|
||||
*/
|
||||
export default 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]);
|
||||
}
|
||||
@ -11,14 +13,16 @@ export default function combineWithoutRepetitions(comboOptions, comboLength) {
|
||||
// Init combinations array.
|
||||
const combos = [];
|
||||
|
||||
// Eliminate characters one by one and concatenate them to
|
||||
// combinations of smaller lengths.
|
||||
// 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));
|
||||
});
|
||||
|
Loading…
Reference in New Issue
Block a user