Last active
March 29, 2020 21:06
-
-
Save susanstevens/f4fc511b27683b63b863148fde48e882 to your computer and use it in GitHub Desktop.
Array Extension to Find All Possible Combinations of a Given Size in Swift
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
extension Array { | |
/** | |
Returns all possible combinations of `k` elements | |
- Parameter k: The size of the combinations to generate | |
- Returns: All possible combinations of `k` elements | |
*/ | |
func combinations(k: Int) -> [[Element]] { | |
guard self.count > 0 && self.count >= k else { return [] } | |
var temp = Array<Element?>(repeating: nil, count: k) | |
var result: [[Element]] = [] | |
findCombinations(input: self, temp: &temp, result: &result, length: k, start: 0) | |
return result | |
} | |
private func findCombinations(input: [Element], | |
temp: inout [Element?], | |
result: inout [[Element]], | |
length: Int, | |
start: Int) { | |
guard length > 0 else { | |
result.append(temp.compactMap { $0 }) | |
return | |
} | |
for i in start...(input.count - length) { | |
temp[temp.count - length] = input[i]; | |
findCombinations(input: input, | |
temp: &temp, | |
result: &result, | |
length: length-1, | |
start: i+1) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment