lottie
Seungjun's blog
blog
순열(permutation)과 조합(combination)

순열(permutation)

순열은 주어진 집합에서 일부를 골라 순서를 고려하여 나열하는 것을 말합니다.

예시 코드

function getPermutations(arr, selectNumber) {
    const results = [];
    if (selectNumber === 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, selectNumber - 1);
        const attached = permutations.map((permutation) => [fixed, ...permutation]);
        results.push(...attached);
    });
  
    return results;
}

console.log(getPermutations([1, 2, 3], 2));


조합(combination)

조합은 주어진 집합에서 일부를 골라 순서를 고려하지 않고 나열하는 것을 말합니다.

예시 코드

function getCombinations(arr, selectNumber) {
    const results = [];
    if (selectNumber === 1) return arr.map((value) => [value]);

    arr.forEach((fixed, index, origin) => {
        const rest = origin.slice(index + 1);
        const combinations = getCombinations(rest, selectNumber - 1);
        const attached = combinations.map((combination) => [fixed, ...combination]);
        results.push(...attached);
    });

    return results;
}

console.log(getCombinations([1, 2, 3], 2));


getPermutations 함수와 getCombinations 함수는 각각 주어진 배열 arr에서 selectNumber개의 요소로 이루어진 모든 순열과 조합을 구합니다.

배열의 각 요소를 고정값으로 설정하고, 나머지 요소들로 순열과 조합을 재귀적으로 구한 후, 고정값과 결합하여 결과를 만듭니다.