Skip to content

Instantly share code, notes, and snippets.

@markmals
Created October 15, 2020 22:30
Show Gist options
  • Save markmals/355e6a7e5afcfe8e9635928305152bc1 to your computer and use it in GitHub Desktop.
Save markmals/355e6a7e5afcfe8e9635928305152bc1 to your computer and use it in GitHub Desktop.
extension Array {
func combine(_ numberOfElements: Int) -> [[Element]] {
guard numberOfElements > 0 else { return [.init()] }
guard let first = first else { return [] }
return Array(dropFirst())
.combine(numberOfElements - 1)
.map { [first] + $0 } +
Array(dropFirst())
.combine(numberOfElements)
}
}
let array = ["a", "b", "c", "d"]
let combined = array.combine(2)
let pairs = [["a", "b"], ["a", "c"], ["a", "d"], ["b", "c"], ["b", "d"], ["c", "d"]]
assert(pairs == combined)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment