Skip to content

Instantly share code, notes, and snippets.

@JCSooHwanCho
Last active April 16, 2021 14:15
Show Gist options
  • Save JCSooHwanCho/f05ac74702db11db57f6fc6a733cea9b to your computer and use it in GitHub Desktop.
Save JCSooHwanCho/f05ac74702db11db57f6fc6a733cea9b to your computer and use it in GitHub Desktop.
Swift로 구현한 모든 조합을 구하는 코드
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