Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /// [1, 2, 3, 4, 5, 6] -> (1,2) (1,3) (1,4) (1,5) (1,6) (2,3) (2,4) (2,5) (2,6) ...
- public func eachToEachIn<C: Collection>(c: C) -> [(left: C.Element, right: C.Element)]? where C.Element: Hashable {
- guard c.count > 1 else { return nil }
- var rightindex = c.startIndex
- var leftindex = c.startIndex
- var controlSet = Set<CoupleUnorderer<C.Element>>()
- while rightindex < c.endIndex {
- while leftindex < c.endIndex {
- let left = c[leftindex]
- let right = c[rightindex]
- if left != right {
- let tuple = CoupleUnorderer(left: left, right: right)
- controlSet.insert(tuple)
- }
- leftindex = c.index(after: leftindex)
- if leftindex == c.endIndex { break }
- }
- leftindex = c.startIndex
- rightindex = c.index(after: rightindex)
- if rightindex == c.endIndex { break }
- }
- return controlSet.map { $0.tuple }
- }
- public struct CoupleUnorderer<Element>: Equatable, Hashable where Element: Hashable {
- public let left: Element
- public let right: Element
- public init(left: Element, right: Element) {
- self.left = left
- self.right = right
- }
- var tuple: (left: Element, right: Element) { (left, right) }
- public static func == (lhs: CoupleUnorderer<Element>, rhs: CoupleUnorderer<Element>) -> Bool {
- let leftset: Set = [lhs.left, lhs.right]
- let rightset: Set = [rhs.left, rhs.right]
- return leftset == rightset
- }
- public func hash(into hasher: inout Hasher) {
- let set: Set = [left, right]
- hasher.combine(set)
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement