조합

확률 및 통계학

2020年12月17日

서로 다른 n개의 원소 중에서 순서에 상관없이 r개를 선택하는 것

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]

AltStyle によって変換されたページ (->オリジナル) /