Last active
May 14, 2017 23:40
-
-
Save chriswebb09/15aa7bc5a1ae484a31054d5be4f6ec21 to your computer and use it in GitHub Desktop.
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 HashTable<Key: Hashable, Value> { | |
typealias Bucket = [HashElement<Key, Value>] | |
var buckets: [Bucket] | |
init(capacity: Int) { | |
assert(capacity > 0) | |
buckets = Array<Bucket>(repeatElement([], count: capacity)) | |
} | |
func index(for key: Key) -> Int { | |
var divisor: Int = 0 | |
for key in String(describing: key).unicodeScalars { | |
divisor += abs(Int(key.value.hashValue)) | |
} | |
return abs(divisor) % buckets.count | |
} | |
func value(for key: Key) -> Value? { | |
let index = self.index(for: key) | |
for element in buckets[index] { | |
if element.key == key { | |
return element.value | |
} | |
} | |
return nil | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment