-
Notifications
You must be signed in to change notification settings - Fork 749
Expand file tree
/
Copy pathCollections.swift
More file actions
94 lines (77 loc) · 2.47 KB
/
Collections.swift
File metadata and controls
94 lines (77 loc) · 2.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
public extension Dictionary {
static func += (lhs: inout Dictionary, rhs: Dictionary) {
lhs.merge(rhs) { (_, new) in new }
}
}
extension Dictionary {
init<S: Sequence>(_ entries: S) where S.Iterator.Element == Element {
self = Dictionary(minimumCapacity: entries.underestimatedCount)
for (key, value) in entries {
self[key] = value
}
}
}
struct GroupedSequence<Key: Equatable, Value> {
private(set) var keys: [Key] = []
fileprivate var groupsForKeys: [[Value]] = []
mutating func append(value: Value, forKey key: Key) -> (Int, Int) {
if let index = keys.firstIndex(where: { $0 == key }) {
groupsForKeys[index].append(value)
return (index, groupsForKeys[index].endIndex - 1)
} else {
keys.append(key)
groupsForKeys.append([value])
return (keys.endIndex - 1, 0)
}
}
}
extension GroupedSequence: Sequence {
func makeIterator() -> GroupedSequenceIterator<Key, Value> {
return GroupedSequenceIterator(base: self)
}
}
struct GroupedSequenceIterator<Key: Equatable, Value>: IteratorProtocol {
private var base: GroupedSequence<Key, Value>
private var keyIterator: EnumeratedSequence<Array<Key>>.Iterator
init(base: GroupedSequence<Key, Value>) {
self.base = base
keyIterator = base.keys.enumerated().makeIterator()
}
mutating func next() -> (Key, [Value])? {
if let (index, key) = keyIterator.next() {
let values = base.groupsForKeys[index]
return (key, values)
} else {
return nil
}
}
}
public func unzip<Element1, Element2>(_ array: [(Element1, Element2)]) -> ([Element1], [Element2]) {
var array1: [Element1] = []
var array2: [Element2] = []
for element in array {
array1.append(element.0)
array2.append(element.1)
}
return (array1, array2)
}
public func unzip<Element1, Element2, Element3>(_ array: [(Element1, Element2, Element3)]) -> ([Element1], [Element2], [Element3]) {
var array1: [Element1] = []
var array2: [Element2] = []
var array3: [Element3] = []
for element in array {
array1.append(element.0)
array2.append(element.1)
array3.append(element.2)
}
return (array1, array2, array3)
}
public func unzip<Element>(_ array: [[Element]], count: Int) -> [[Element]] {
var unzippedArray: [[Element]] = Array(repeating: [], count: count)
for valuesForElement in array {
for (index, value) in valuesForElement.enumerated() {
unzippedArray[index].append(value)
}
}
return unzippedArray
}