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) {
25 alreadyAdded.insert($0)
34 func appended(_ elem: () -> Element) -> Array {
36 return self + [elem()]
40 infix operator ==? : ComparisonPrecedence
41 func ==? <T: Comparable> (lhv: T, rhv: T) -> ComparisonResult {
49 return .orderedAscending
52 return .orderedDescending
55 extension MutableCollection {
57 private func bsearch(min: Int, max: Int, comparator: (Iterator.Element) -> ComparisonResult) -> Iterator.Element? {
64 let current = min + (max - min) / 2
65 let v = self[self.index(self.startIndex, offsetBy: current)]
66 let compRes = comparator(v)
68 if compRes == .orderedSame {
73 let newMin = (compRes == .orderedAscending) ? current + 1 : min
74 let newMax = (compRes == .orderedDescending) ? current - 1 : max
76 return bsearch(min: newMin, max: newMax, comparator: comparator)
79 func binarySearch(comparator: (Iterator.Element) -> ComparisonResult) -> Iterator.Element? {
81 return bsearch(min: 0, max: self.count - 1, comparator: comparator)