티스토리 뷰

자바스크립트

순열과 조합

안양사람 2020. 12. 29. 20:45
728x90
SMALL

조합먼저 코드를 이해하면 쉬움

 

순열 알고리즘

const getPermutations = function (arr, selectNumber) {
  const results = [];
  if (selectNumber === 1) return arr.map((i) => [i]); // 1개씩 선택한다면 모든 배열의 원소를 return한다.

  arr.forEach((fixed, index, array) => {
    const rest = [...array.slice(0, index), ...array.slice(index + 1)]; // fixed를 제외한 나머지 배열(순열)
    const permutations = getPermutations(rest, selectNumber - 1); // rest에 대한 순열을 구한다.
    const attached = permutations.map((permutation) => [fixed, ...permutation]); // fixed와 rest에 대한 조합을 붙인다.
    results.push(...attached); // result 배열에 push
  });

  return results;
};

순열 예시

var example = ["a", "b", "c"];
var result = getPermutations(example, 2);
console.log(result);

var example = [1, 2, 3, 4];
var result = getPermutations(example, 3);
console.log(result);

 

조합 알고리즘

const getCombinations = (arr, selectNumber) => {
  const result = [];
  if (selectNumber === 1) return arr.map((i) => [i]); // 1개씩 선택한다면 모든 배열의 원소를 return한다.
  
  arr.forEach((fixed, index, array) => {
    const rest = array.slice(index + 1); // fixed의 다음 index 부터 끝까지의 배열(조합)
    const combinations = getCombinations(rest, selectNumber - 1); // rest에 대한 조합을 구한다.
    const attached = combinations.map((combination) => [fixed, ...combination]); // fixed와 rest에 대한 조합을 붙인다.
    result.push(...attached); // result 배열에 push
  });
  
  return result;
};

조합 예시

var example = ["a", "b", "c"];
var result = getCombinations(example, 2);
console.log(result);

var example = [1, 2, 3, 4];
var result = getCombinations(example, 2);
console.log(result);

 

출처

jun-choi-4928.medium.com/javascript%EB%A1%9C-%EC%88%9C%EC%97%B4%EA%B3%BC-%EC%A1%B0%ED%95%A9-%EC%95%8C%EA%B3%A0%EB%A6%AC%EC%A6%98-%EA%B5%AC%ED%98%84%ED%95%98%EA%B8%B0-21df4b536349

 

JavaScript로 순열과 조합 알고리즘 구현하기

재귀, JavaScript Array Methods

jun-choi-4928.medium.com

 

유투브

https://www.youtube.com/watch?v=IBRB1dv-Akw&ab_channel=%EC%9C%A4%EC%9C%A4 

 

728x90
LIST
댓글
공지사항