Devlog/Coding Practice
[JS] 배열 요소들의 모든 조합(Combinations) 구하기
FATKITTY
2022. 5. 4. 17:41
반응형
function getCombinations(arr, N) {
const results = [];
if (N === 1) return arr.map((value) => [value]);
arr.forEach((fixed, index, origin) => {
const rest = origin.slice(index + 1);
// 해당하는 fixed를 제외한 나머지 뒤
const combinations = getCombinations(rest, N - 1);
// 나머지에 대해서 조합을 구한다.
const attached = combinations.map((combination) => [fixed, ...combination]);
// 돌아온 조합에 떼 놓은(fixed) 값 붙이기
results.push(...attached);
});
return results;
}
참고자료
https://pul8219.github.io/algorithm/algorithm-permutation-and-combination/
반응형