Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #276 from JaapWijnen/hashsetswift3
Hashset migrate to swift3
- Loading branch information
Showing
3 changed files
with
130 additions
and
122 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,76 @@ | ||
//: Playground - noun: a place where people can play | ||
|
||
public struct HashSet<T: Hashable> { | ||
fileprivate var dictionary = Dictionary<T, Bool>() | ||
|
||
public init() { | ||
|
||
} | ||
|
||
public mutating func insert(_ element: T) { | ||
dictionary[element] = true | ||
} | ||
|
||
public mutating func remove(_ element: T) { | ||
dictionary[element] = nil | ||
} | ||
|
||
public func contains(_ element: T) -> Bool { | ||
return dictionary[element] != nil | ||
} | ||
|
||
public func allElements() -> [T] { | ||
return Array(dictionary.keys) | ||
} | ||
|
||
public var count: Int { | ||
return dictionary.count | ||
} | ||
|
||
public var isEmpty: Bool { | ||
return dictionary.isEmpty | ||
} | ||
} | ||
|
||
/* Union */ | ||
|
||
extension HashSet { | ||
public func union(_ otherSet: HashSet<T>) -> HashSet<T> { | ||
var combined = HashSet<T>() | ||
for obj in self.dictionary.keys { | ||
combined.insert(obj) | ||
} | ||
for obj in otherSet.dictionary.keys { | ||
combined.insert(obj) | ||
} | ||
return combined | ||
} | ||
} | ||
|
||
/* Intersection */ | ||
|
||
extension HashSet { | ||
public func intersect(_ otherSet: HashSet<T>) -> HashSet<T> { | ||
var common = HashSet<T>() | ||
for obj in dictionary.keys { | ||
if otherSet.contains(obj) { | ||
common.insert(obj) | ||
} | ||
} | ||
return common | ||
} | ||
} | ||
|
||
/* Difference */ | ||
|
||
extension HashSet { | ||
public func difference(_ otherSet: HashSet<T>) -> HashSet<T> { | ||
var diff = HashSet<T>() | ||
for obj in dictionary.keys { | ||
if !otherSet.contains(obj) { | ||
diff.insert(obj) | ||
} | ||
} | ||
return diff | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters