본문 바로가기
개발/알고리즘

내가 보려고 만든 순열 조합 중복순열

by 안뇽! 2021. 10. 7.
반응형

순열

//순열

const getPermutations = function (arr, selectNumber) {
  // - 순열을 담을 배열 설정
  const results = [];
  // - base case: 숫자가 한개라면 숫자 그대로 배열로 반환
  if (selectNumber === 1) return arr.map((value) => [value]);
  // - recursive case: arr을 순회하면서 각 숫자들을 fixed하여 첫번째 수로 만든다.
  arr.forEach((fixed, index, origin) => {
    // - fixed를 제외한 나머지 배열을 만든다.
    const rest = [...origin.slice(0, index), ...origin.slice(index + 1)];
    // - 나머지에 대해서 재귀함수를 통해 순열을 만든다.
    const permutations = getPermutations(rest, selectNumber - 1);
    // - 각각 만들어진 순열 앞에 고정시킨 수(fixed)를 넣는다.
    const attached = permutations.map((permutation) => [fixed, ...permutation]);
    // - 그리고 만들어진 순열들을 스프레드 연산자로 result에 push한다.
    results.push(...attached);
  });
  // - result를 반환
  return results;
};

 

조합

const getCombinations = function (arr, selectNumber) {
  // - 순열을 담을 배열 설정
  const results = [];
  // - base case: 숫자가 한개라면 숫자 그대로 배열로 반환
  if (selectNumber === 1) return arr.map((value) => [value]);
  // - recursive case: arr을 순회하면서 각 숫자들을 fixed하여 첫번째 수로 만든다.
  arr.forEach((fixed, index, origin) => {
    
    const rest = origin.slice(index + 1);
    // - 나머지에 대해서 재귀함수를 통해 순열을 만든다.
    const combinations = getCombinations(rest, selectNumber - 1);
    // - 각각 만들어진 순열 앞에 고정시킨 수(fixed)를 넣는다.
    const attached = combinations.map((combination) => [fixed, ...combination]);
    // - 그리고 만들어진 순열들을 스프레드 연산자로 result에 push한다.
    results.push(...attached);
  });
  // - result를 반환
  return results;
};

중복순열

//중복순열
const getPermutations = function (arr, selectNumber) {
  // - 순열을 담을 배열 설정
  const results = [];
  // - base case: 숫자가 한개라면 숫자 그대로 배열로 반환
  if (selectNumber === 1) return arr.map((value) => [value]);
  // - recursive case: arr을 순회하면서 각 숫자들을 fixed하여 첫번째 수로 만든다.
  arr.forEach((fixed, index, origin) => {
    // 중복이 허용된다.
    const rest = origin.slice()
    // - 나머지에 대해서 재귀함수를 통해 순열을 만든다.
    const permutations = getPermutations(rest, selectNumber - 1);
    // - 각각 만들어진 순열 앞에 고정시킨 수(fixed)를 넣는다.
    const attached = permutations.map((permutation) => [fixed, ...permutation]);
    // - 그리고 만들어진 순열들을 스프레드 연산자로 result에 push한다.
    results.push(...attached);
  });
  // - result를 반환
  return results;
};
반응형