So you want to generate all permutations from size = 1 to size = N?
Stack Overflow user Andy Carson has created a JavaScript library with a permutation generator function that lets you specify size.
See: GitHub / acarl005 / Generatorics
// Adapted from: https://stackoverflow.com/a/41232141/1762224
// Uses: https://github.com/acarl005/generatorics
const allPermutations = (arr) =>
Array.from({ length: arr.length }, (_, index) =>
Array.from(G.permutation(arr, index + 1), (v) => v.join(''))).flat();
// Output: [a b ab ba]
console.log(...allPermutations(['a', 'b']));
// Output: [x y z xy xz yx yz zx zy xyz xzy yxz yzx zyx zxy]
console.log(...allPermutations(['x', 'y', 'z']));
.as-console-wrapper { top: 0; max-height: 100% !important; }
<script src="https://cdn.jsdelivr.net/gh/acarl005/generatorics/generatorics.js"></script>
If you want to allow duplicates, you can try:
// Adapted from: https://gist.github.com/jonschlinkert/730a2deba6d4a25850e06105be0a279a
const __permute = (value, depth, results, queue = []) => {
if (queue.length === depth) results.push(queue);
else for (let ele of value) __permute(value, depth, results, queue.concat(ele));
};
const permutationsWithDupes = (value, max = value.length) => {
let depth = Math.min(max, value.length), results = [];
__permute(value, depth, results);
return results;
};
const allPermutationsWithDupes = (arr) => {
const results = [];
for (let size = 1; size <= arr.length; size++) {
results.push(...permutationsWithDupes(arr, size));
}
return results.map(v => v.join(''));
}
// Output: [a b aa ab ba bb]
console.log(...allPermutationsWithDupes(['a', 'b']));
.as-console-wrapper { top: 0; max-height: 100% !important; }
solved All combination with JS [closed]