Skip to content

Instantly share code, notes, and snippets.

@zlrlo
Created October 3, 2023 02:40
Show Gist options
  • Select an option

  • Save zlrlo/d13270f9a34a286ebf724b10db085bdc to your computer and use it in GitHub Desktop.

Select an option

Save zlrlo/d13270f9a34a286ebf724b10db085bdc to your computer and use it in GitHub Desktop.
[JS] 순열 구현
function permutations(arr, n) {
// 1개만 뽑는다면 그대로 순열을 반환한다. 탈출 조건으로도 사용된다.
if (n === 1) return arr.map((v) => [v]);
let result = [];
// 요소를 순환한다
arr.forEach((fixed, idx, arr) => {
// 현재 index를 제외한 요소를 추출한다.
// index번째는 선택된 요소
const rest = arr.filter((_, index) => index !== idx);
// 선택된 요소를 제외하고 재귀 호출한다.
const perms = permutations(rest, n - 1);
// 선택된 요소와 재귀 호출을 통해 구한 순열을 합쳐준다.
const combine = perms.map((v) => [fixed, ...v]);
// 결과 값을 추가한다.
result.push(...combine);
});
// 결과 반환
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment