Created
October 10, 2023 04:56
-
-
Save brownsoo/efe5552117e056a6d0fa098a7a0a9c09 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 getPermutations(_ arr: [Book], select: Int) -> [[Book]] { | |
var results: [[Book]] = [] | |
if select == 1 { | |
return arr.map { [$0] } | |
} | |
arr.enumerated().forEach { el in | |
let rest = Array(arr[(el.offset + 1)..<arr.count]) | |
let permutations = getPermutations(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