Created
January 7, 2020 16:48
-
-
Save erkekin/fe037bce179ec8f860788130aa9c15ea to your computer and use it in GitHub Desktop.
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
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