2 // ArrayExtensions.swift
5 // Created by Hori,Masaki on 2017/03/01.
6 // Copyright © 2017年 Hori,Masaki. All rights reserved.
12 // powerd by http://qiita.com/su_k/items/157e4c6e390944237253
13 extension Array where Element: Hashable {
15 func unique() -> [Element] {
18 r += !r.contains(i) ? [i] : []
23 mutating func uniqueInPlace() {
30 func appended(_ elem: () -> Element) -> Array {
31 return self + [elem()]
35 infix operator ==? : ComparisonPrecedence
36 func ==? <T: Comparable> (lhv: T, rhv: T) -> ComparisonResult {
37 if lhv == rhv { return .orderedSame }
38 if lhv < rhv { return .orderedAscending }
39 return .orderedDescending
42 extension MutableCollection where IndexDistance == Int {
43 private func bsearch(min: Int, max: Int, comparator: (Iterator.Element) -> ComparisonResult) -> Iterator.Element? {
44 if max < min { return nil }
45 let current = min + (max - min) / 2
46 let v = self[self.index(self.startIndex, offsetBy: current)]
47 let compRes = comparator(v)
49 if compRes == .orderedSame { return v }
51 let newMin = (compRes == .orderedAscending) ? current + 1 : min
52 let newMax = (compRes == .orderedDescending) ? current - 1 : max
53 return bsearch(min: newMin, max: newMax, comparator: comparator)
56 func binarySearch(comparator: (Iterator.Element) -> ComparisonResult) -> Iterator.Element? {
57 return bsearch(min: 0, max: self.count - 1, comparator: comparator)