Skip to content

Instantly share code, notes, and snippets.

@potados99
Created May 10, 2022 01:37
Show Gist options
  • Save potados99/27b71699dc1570672571527bd1a1da2b to your computer and use it in GitHub Desktop.
Save potados99/27b71699dc1570672571527bd1a1da2b to your computer and use it in GitHub Desktop.
자바스크립트로 배열 조합 구하기
function combination(source, howMany = source.length) {
const result = [];
const sourceLength = source.length;
const pow = (workingCombo, currentIndex, remainingCount) => {
for (let i = currentIndex; i < sourceLength; i++) {
const nextWorkingCombo = [...workingCombo, source[i]];
if (remainingCount === 1) {
// 이번 호출은 마지막 단계이니,
// 루프마다 완성된 nextWorkingCombo를 바로 결과에 추가해줍니다.
result.push(nextWorkingCombo);
} else {
// 하나 더 뽑는 다음 호출을 진행합니다.
pow(nextWorkingCombo, i + 1, remainingCount - 1);
}
}
};
pow([], 0, howMany);
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment