const getPermutations = (arr, selectNumber) => {
const results = [];
if (selectNumber === 1) return arr.map(value => [value]);
arr.forEach((fixed, index, origin) => {
const rest = [...origin.slice(0, index), ...origin.slice(index + 1)];
const combinations = getPermutations(rest, selectNumber - 1);
const attached = combinations.map(combination => [fixed, ...combination]);
results.push(...attached);
});
return results;
};
입력
const arr = [1, 2, 3, 4, 5];
const selectNumber = 2;
출력
[1, 2]
[1, 3]
[1, 4]
[1, 5]
[2, 1]
[2, 3]
[2, 4]
[2, 5]
[3, 1]
[3, 2]
[3, 4]
[3, 5]
[4, 1]
[4, 2]
[4, 3]
[4, 5]
[5, 1]
[5, 2]
[5, 3]
[5, 4]