File tree Expand file tree Collapse file tree 2 files changed +8
-16
lines changed
Multiset.playground/Sources Expand file tree Collapse file tree 2 files changed +8
-16
lines changed Original file line number Diff line number Diff line change 8
8
import Foundation
9
9
10
10
public struct Multiset < Element: Hashable > {
11
- fileprivate var storage : [ Element : UInt ]
12
- private var _count : UInt = 0
11
+ private var storage : [ Element : UInt ] = [ : ]
12
+ public private( set ) var count : UInt = 0
13
13
14
- public init ( ) {
15
- storage = [ : ]
16
- }
14
+ public init ( ) { }
17
15
18
16
public mutating func add ( _ elem: Element ) {
19
- if let currentCount = storage [ elem] {
20
- storage [ elem] = currentCount + 1 ;
21
- } else {
22
- storage [ elem] = 1
23
- }
24
- _count += 1
17
+ storage [ elem, default: 0 ] += 1
18
+ count += 1
25
19
}
26
20
27
21
public mutating func remove ( _ elem: Element ) {
@@ -31,7 +25,7 @@ public struct Multiset<Element: Hashable> {
31
25
} else {
32
26
storage. removeValue ( forKey: elem)
33
27
}
34
- _count -= 1
28
+ count -= 1
35
29
}
36
30
}
37
31
@@ -45,10 +39,6 @@ public struct Multiset<Element: Hashable> {
45
39
return true
46
40
}
47
41
48
- public var count : UInt {
49
- return _count
50
- }
51
-
52
42
public func count( for key: Element ) -> UInt {
53
43
return storage [ key] ?? 0
54
44
}
Original file line number Diff line number Diff line change @@ -87,3 +87,5 @@ public func count(for key: Element) -> UInt {
87
87
return storage[key] ?? 0
88
88
}
89
89
```
90
+
91
+ * Written for the Swift Algorithm Club by Simon Whitaker*
You can’t perform that action at this time.
0 commit comments