2 // ArrayExtensions.swift
5 // Created by Hori,Masaki on 2017/03/01.
6 // Copyright © 2017年 Hori,Masaki. All rights reserved.
11 // powered by http://stackoverflow.com/questions/40579554/how-to-display-unique-elements-of-an-array-using-swift
12 extension Sequence where Iterator.Element: Hashable {
14 func unique() -> [Iterator.Element] {
16 var alreadyAdded = Set<Iterator.Element>()
20 if alreadyAdded.contains($0) { return false }
22 alreadyAdded.insert($0)
31 func appended(_ elem: () -> Element) -> Array {
33 return self + [elem()]
37 infix operator ==? : ComparisonPrecedence
38 func ==? <T: Comparable> (lhv: T, rhv: T) -> ComparisonResult {
40 if lhv == rhv { return .orderedSame }
41 if lhv < rhv { return .orderedAscending }
43 return .orderedDescending
46 extension MutableCollection where IndexDistance == Int {
48 private func bsearch(min: Int, max: Int, comparator: (Iterator.Element) -> ComparisonResult) -> Iterator.Element? {
50 if max < min { return nil }
52 let current = min + (max - min) / 2
53 let v = self[self.index(self.startIndex, offsetBy: current)]
54 let compRes = comparator(v)
56 if compRes == .orderedSame { return v }
58 let newMin = (compRes == .orderedAscending) ? current + 1 : min
59 let newMax = (compRes == .orderedDescending) ? current - 1 : max
61 return bsearch(min: newMin, max: newMax, comparator: comparator)
64 func binarySearch(comparator: (Iterator.Element) -> ComparisonResult) -> Iterator.Element? {
66 return bsearch(min: 0, max: self.count - 1, comparator: comparator)