순열(Permutation)

Yeon Jeffrey Seo·2021년 12월 13일

알고리즘

목록 보기
1/1

서로 다른 n개의 물건 중에서 r개를 택하여 한 줄로 세우는 것을 n개의 물건에서 r개 택하는 순열이라 하고, 기호로는 nPr로 표현한다. 한 줄로 세운다는 것은 순서가 중요하다는 의미이다.

const getPermutations = function (arr, selectNumber) {
    const results = [];
    if (selectNumber === 1) return arr.map((el) => [el]); 
    // n개중에서 1개 선택할 때(nP1), 바로 모든 배열의 원소 return. 1개선택이므로 순서가 의미없음.

    arr.forEach((fixed, index, origin) => {
      const rest = [...origin.slice(0, index), ...origin.slice(index+1)] 
      // 해당하는 fixed를 제외한 나머지 배열 
      const permutations = getPermutations(rest, selectNumber - 1); 
      // 나머지에 대해서 순열을 구한다.
      const attached = permutations.map((el) => [fixed, ...el]); 
      //  돌아온 순열에 떼 놓은(fixed) 값 붙이기
      results.push(...attached); 
      // 배열 spread syntax 로 모두다 push
    });

    return results; // 결과 담긴 results return
}
profile
The best time to plant a tree was twenty years ago. The second best time is now.

0개의 댓글