mirror of
https://github.com/trekhleb/javascript-algorithms.git
synced 2025-12-08 19:06:00 +00:00
32 lines
827 B
JavaScript
32 lines
827 B
JavaScript
/**
|
|
* @param {*[]} permutationOptions
|
|
* @param {number} permutationLength
|
|
* @return {*[]}
|
|
*/
|
|
export default function permutateWithRepetitions(
|
|
permutationOptions,
|
|
permutationLength = permutationOptions.length,
|
|
) {
|
|
if (permutationLength === 1) {
|
|
return permutationOptions.map((permutationOption) => [permutationOption]);
|
|
}
|
|
|
|
// Init permutations array.
|
|
const permutations = [];
|
|
|
|
// Get smaller permutations.
|
|
const smallerPermutations = permutateWithRepetitions(
|
|
permutationOptions,
|
|
permutationLength - 1,
|
|
);
|
|
|
|
// Go through all options and join it to the smaller permutations.
|
|
permutationOptions.forEach((currentOption) => {
|
|
smallerPermutations.forEach((smallerPermutation) => {
|
|
permutations.push([currentOption].concat(smallerPermutation));
|
|
});
|
|
});
|
|
|
|
return permutations;
|
|
}
|