티스토리 뷰
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);
출처
유투브
https://www.youtube.com/watch?v=IBRB1dv-Akw&ab_channel=%EC%9C%A4%EC%9C%A4
728x90
LIST
'자바스크립트' 카테고리의 다른 글
타입스크립트에서 클래스 타입 지정하기 (0) | 2022.01.09 |
---|---|
자바스크립트 정리 (0) | 2021.04.27 |
자바스크립트 클래스 변경 전후 (1) | 2020.12.17 |
array.from, fill, includes (0) | 2020.12.17 |
객체 배열 index찾기 (0) | 2020.08.30 |
댓글
공지사항