OSDN Git Service

コメントを追加
[kcd/KCD.git] / KCD / ArrayExtensions.swift
1 //
2 //  ArrayExtensions.swift
3 //  KCD
4 //
5 //  Created by Hori,Masaki on 2017/03/01.
6 //  Copyright © 2017年 Hori,Masaki. All rights reserved.
7 //
8
9 import Foundation
10
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 {
13     
14     func unique() -> [Iterator.Element] {
15         
16         var alreadyAdded = Set<Iterator.Element>()
17         
18         return filter {
19             
20             if alreadyAdded.contains($0) { return false }
21             
22             alreadyAdded.insert($0)
23             
24             return true
25         }
26     }
27 }
28
29 extension Array {
30     
31     func appended(_ elem: () -> Element) -> Array {
32         
33         return self + [elem()]
34     }
35 }
36
37 infix operator ==? : ComparisonPrecedence
38 func ==? <T: Comparable> (lhv: T, rhv: T) -> ComparisonResult {
39     
40     if lhv == rhv { return .orderedSame }
41     if lhv < rhv { return .orderedAscending }
42     
43     return .orderedDescending
44 }
45
46 extension MutableCollection where IndexDistance == Int {
47     
48     private func bsearch(min: Int, max: Int, comparator: (Iterator.Element) -> ComparisonResult) -> Iterator.Element? {
49         
50         if max < min { return nil }
51         
52         let current = min + (max - min) / 2
53         let v = self[self.index(self.startIndex, offsetBy: current)]
54         let compRes = comparator(v)
55         
56         if compRes == .orderedSame { return v }
57         
58         let newMin = (compRes == .orderedAscending) ? current + 1 : min
59         let newMax = (compRes == .orderedDescending) ? current - 1 : max
60         
61         return bsearch(min: newMin, max: newMax, comparator: comparator)
62     }
63     
64     func binarySearch(comparator: (Iterator.Element) -> ComparisonResult) -> Iterator.Element? {
65         
66         return bsearch(min: 0, max: self.count - 1, comparator: comparator)
67     }
68 }