const getCombinations = (arr, selectNumber) => {
if (selectNumber === 1) {
return arr.map(value => [value]);
}
return arr.reduce((acc, fixedNumber, index) => {
const rest = arr.slice(index + 1);
const combinations = getCombinations(rest, selectNumber - 1);
const attached = combinations.map(combination => [
fixedNumber,
...combination,
]);
return acc.concat(attached);
}, []);
};
입력
const arr = [1, 2, 3, 4, 5];
const selectNumber = 2;
출력
[1, 2]
[1, 3]
[1, 4]
[1, 5]
[2, 3]
[2, 4]
[2, 5]
[3, 4]
[3, 5]
[4, 5]