Last active
October 10, 2023 04:57
-
-
Save brownsoo/085cfe33087055d15e4da440f23c7e49 to your computer and use it in GitHub Desktop.
배열 요소의 모든 조합 구하기 (순열, 순서고려)
This file contains 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
/// 배열의 모든 조합 구하기 (순열) | |
/// 순서에 상관하여 같은 요소라도 순서가 다르면 다른 조합으로 처리 | |
/// - Parameters: | |
/// - arr: 제공되는 배열 | |
/// - select: 몇개의 요소를 선택해서 조합할지 결정 | |
/// - Returns: 제공된 배열에서 select 개를 선택해서 조합된 새 배열 | |
func getAllPermutations(_ arr: [Int], select: Int) -> [[Int]] { | |
var results: [[Int]] = [] | |
if select == 1 { | |
return arr.map { [$0] } | |
} | |
arr.enumerated().forEach { el in | |
let rest = Array(arr[0..<el.offset] + arr[(el.offset + 1)..<arr.count]) | |
let permutations = getAllPermutations(rest, select: select - 1) | |
let attached = permutations.map({ [el.element] + $0 }) | |
results.append(contentsOf: attached) | |
} | |
return results | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment