Last active
June 17, 2019 20:22
-
-
Save davidinga/adc0a1c4f6432ff432387550e231f06c to your computer and use it in GitHub Desktop.
Hash Table with chaining that stores the keys only.
This file contains hidden or 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
| struct HashTableOnlyKeys<Key: Hashable> { | |
| typealias Element = Key | |
| typealias List = SinglyLinkedList<Element> | |
| private var table: [List] | |
| private(set) public var count = 0 | |
| public var size: Int { | |
| return table.count | |
| } | |
| var isEmpty: Bool { | |
| return count == 0 | |
| } | |
| init(size: Int) { | |
| assert(size > 0) | |
| table = Array<List>() | |
| for _ in 0..<size { | |
| let list = List() | |
| table += [list] | |
| } | |
| } | |
| func contains(_ key: Key) -> Key? { | |
| let index = self.index(forKey: key) | |
| var node = table[index].first | |
| while node != nil { | |
| if node!.element == key { | |
| return key | |
| } | |
| node = node!.next | |
| } | |
| return nil | |
| } | |
| mutating func append(_ key: Key) { | |
| let index = self.index(forKey: key) | |
| var node = table[index].first | |
| while node != nil { | |
| node = node!.next | |
| } | |
| table[index].append(key) | |
| count += 1 | |
| } | |
| @discardableResult mutating func remove(_ key: Key) -> Key? { | |
| let index = self.index(forKey: key) | |
| var node = table[index].first | |
| while node != nil { | |
| if node!.element == key { | |
| count -= 1 | |
| return table[index].remove(node: node!)!.element | |
| } | |
| node = node!.next | |
| } | |
| return nil | |
| } | |
| mutating func removeAll() { | |
| table = Array<List>(repeatElement(List(), count: table.count)) | |
| count = 0 | |
| } | |
| func index(forKey key: Key) -> Int { | |
| return abs(key.hashValue % table.count) | |
| } | |
| } | |
| struct HashTableOnlyKeysIterator<Element: Hashable>: IteratorProtocol { | |
| private let table: HashTableOnlyKeys<Element> | |
| private var index = 0 | |
| init(_ table: HashTableOnlyKeys<Element>) { | |
| self.table = table | |
| } | |
| mutating func next() -> Element? { | |
| let element = table.value(at: index) | |
| index += 1 | |
| return element | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment