Created
October 3, 2023 02:40
-
-
Save zlrlo/d13270f9a34a286ebf724b10db085bdc to your computer and use it in GitHub Desktop.
[JS] 순열 구현
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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