Skip to content

Instantly share code, notes, and snippets.

@chriswebb09
Last active May 14, 2017 23:40
Show Gist options
  • Save chriswebb09/15aa7bc5a1ae484a31054d5be4f6ec21 to your computer and use it in GitHub Desktop.
Save chriswebb09/15aa7bc5a1ae484a31054d5be4f6ec21 to your computer and use it in GitHub Desktop.
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