Skip to content

Instantly share code, notes, and snippets.

@erkekin
Created January 7, 2020 16:48
Show Gist options
  • Save erkekin/fe037bce179ec8f860788130aa9c15ea to your computer and use it in GitHub Desktop.
Save erkekin/fe037bce179ec8f860788130aa9c15ea to your computer and use it in GitHub Desktop.
extension Set {
private func addCombination(prevCombo: [Element], pivotList: [Element]) -> [([Element], [Element])] {
var pivotList = pivotList
return (0..<pivotList.count)
.map { _ -> ([Element], [Element]) in
(prevCombo + [pivotList.remove(at: 0)], pivotList)
}
}
func combinations(m: Int) -> [[Element]] {
var initial = [([Element](), Array(self))]
for _ in 1...m {
initial = initial.flatMap(addCombination)
}
return initial.map{$0.0}
}
}
let set = Set([1,2,3,4])
set.combinations(m: 3)
// [[3, 1, 4], [3, 1, 2], [3, 4, 2], [1, 4, 2]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment