Last active
April 16, 2021 14:15
-
-
Save JCSooHwanCho/f05ac74702db11db57f6fc6a733cea9b to your computer and use it in GitHub Desktop.
Swift로 구현한 모든 조합을 구하는 코드
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
func getCombination<T>(elements:[T], select: Int, repetition: Bool) -> [[T]] { | |
func getCombination<T>(elements: ArraySlice<T>, select: Int, repetition: Bool, partialResult: inout [T], totalResult: inout [[T]]) { | |
guard select > 0 else { | |
totalResult.append(partialResult) | |
return | |
} | |
guard let firstElement = elements.first else { return } | |
let remains = repetition ? elements : elements.dropFirst() | |
partialResult.append(firstElement) | |
getCombination(elements: remains, select: select-1, repetition: repetition, partialResult: &partialResult, totalResult: &totalResult) | |
partialResult.removeLast() | |
getCombination(elements: elements.dropFirst(), select: select, repetition: repetition, partialResult: &partialResult, totalResult: &totalResult) | |
} | |
var result: [[T]] = [] | |
var partialResult: [T] = [] | |
getCombination(elements: elements[…], select: select, repetition: repetition, partialResult: &partialResult, totalResult: &result) | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment