순열과 조합 설명:
자바스크립트로의 간략한 구현 예:
// 순열
function getPermutations(arr, selectNum) {
const results = [];
if (selectNum === 1) return arr.map((value) => [value]);
arr.forEach((fixed, index, origin) => {
const rest = [...origin.slice(0, index), ...origin.slice(index+1)];
const permutations = getPermutations(rest, selectNum - 1);
const attached = permutations.map((permutation) => [fixed, ...permutation]);
results.push(...attached);
});
return results;
}
// 조합
function getCombinations(arr, selectNum) {
const results = [];
if (selectNum === 1) return arr.map((value) => [value]);
arr.forEach((fixed, index, origin) => {
const rest = origin.slice(index + 1);
const combinations = getCombinations(rest, selectNum - 1);
const attached = combinations.map((combination) => [fixed, ...combination]);
results.push(...attached);
});
return results;
}
console.log(getPermutations(['A', 'B', 'C'], 2)); // 출력: [ [ 'A', 'B' ], [ 'A', 'C' ], [ 'B', 'A' ], [ 'B', 'C' ], [ 'C', 'A' ], [ 'C', 'B' ] ]
console.log(getCombinations(['A', 'B', 'C'], 2)); // 출력: [ [ 'A', 'B' ], [ 'A', 'C' ], [ 'B', 'C' ] ]
순열과 조합은 특히 조합 최적화 문제, 퍼즐, 브루트포스 탐색 등에서 유용하게 사용됩니다.