순열과 조합

dowon kim·2023년 9월 3일

순열과 조합 설명:

  1. 순열 (Permutation):
    • 순열은 주어진 n개의 원소 중에서 r개를 선택하여 일렬로 나열하는 것을 말합니다.
    • 순서가 의미가 있기 때문에 같은 원소들이더라도 순서가 다르면 다른 순열로 취급됩니다.
    • 예를 들면, {A, B, C}에서 2개를 선택하는 순열은 {A, B}, {A, C}, {B, A}, {B, C}, {C, A}, {C, B}입니다.
  2. 조합 (Combination):
    • 조합은 주어진 n개의 원소 중에서 r개를 선택하는 것을 말합니다.
    • 순서는 고려하지 않기 때문에 순서가 바뀌어도 같은 조합으로 취급됩니다.
    • 예를 들면, {A, B, C}에서 2개를 선택하는 조합은 {A, B}, {A, C}, {B, C}입니다.

자바스크립트로의 간략한 구현 예:

// 순열
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' ] ]

순열과 조합은 특히 조합 최적화 문제, 퍼즐, 브루트포스 탐색 등에서 유용하게 사용됩니다.

profile
The pain is so persistent that it is like a snail, and the joy is so short that it is like a rabbit's tail running through the fields of autumn

0개의 댓글