Advertisement
SEEEEEAAAAAA10000000

Each To Each (Generic)

Sep 30th, 2019
240
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.64 KB | None | 0 0
  1. /// [1, 2, 3, 4, 5, 6] -> (1,2) (1,3) (1,4) (1,5) (1,6) (2,3) (2,4) (2,5) (2,6) ...
  2.  
  3. public func eachToEachIn<C: Collection>(c: C) -> [(left: C.Element, right: C.Element)]?  where C.Element: Hashable {
  4.     guard c.count > 1 else { return nil }
  5.     var rightindex = c.startIndex
  6.     var leftindex = c.startIndex
  7.     var controlSet = Set<CoupleUnorderer<C.Element>>()
  8.     while rightindex < c.endIndex {
  9.         while leftindex < c.endIndex {
  10.             let left = c[leftindex]
  11.             let right = c[rightindex]
  12.             if left != right {
  13.                 let tuple = CoupleUnorderer(left: left, right: right)
  14.                 controlSet.insert(tuple)
  15.             }
  16.             leftindex = c.index(after: leftindex)
  17.             if leftindex == c.endIndex { break }
  18.         }
  19.         leftindex = c.startIndex
  20.         rightindex = c.index(after: rightindex)
  21.         if rightindex == c.endIndex { break }
  22.     }
  23.     return controlSet.map { $0.tuple }
  24. }
  25.  
  26. public struct CoupleUnorderer<Element>: Equatable, Hashable where Element: Hashable {
  27.     public let left: Element
  28.     public let right: Element
  29.     public init(left: Element, right: Element) {
  30.         self.left = left
  31.         self.right = right
  32.     }
  33.     var tuple: (left: Element, right: Element) { (left, right) }
  34.     public static func == (lhs: CoupleUnorderer<Element>, rhs: CoupleUnorderer<Element>) -> Bool {
  35.         let leftset: Set = [lhs.left, lhs.right]
  36.         let rightset: Set = [rhs.left, rhs.right]
  37.         return leftset == rightset
  38.     }
  39.     public func hash(into hasher: inout Hasher) {
  40.         let set: Set = [left, right]
  41.         hasher.combine(set)
  42.     }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement