Last active
June 2, 2017 12:07
-
-
Save TeWu/1785156 to your computer and use it in GitHub Desktop.
Simple Hashtable implementation (hash collision resolution with open adressing)
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
class Hashtable | |
INITIAL_TABLE_SIZE = 32 | |
Entry = Struct.new(:key, :value) | |
def initialize | |
@table = Array.new(INITIAL_TABLE_SIZE) | |
end | |
attr_accessor :table | |
def []=(key, value) | |
start_index = index = to_index(key) | |
while @table[index] != nil && @table[index].key != key | |
index = (index + 1) % @table.size | |
expand_table_length if index == start_index | |
end | |
@table[index] = Entry.new(key, value) | |
end | |
def [](key) | |
start_index = index = to_index(key) | |
while @table[index] == nil || @table[index].key != key | |
index = (index + 1) % @table.size | |
return nil if index == start_index | |
end | |
@table[index].value | |
end | |
private | |
def to_index(obj) | |
obj.hash.abs % @table.size | |
end | |
def expand_table_length | |
old_table = @table | |
@table = Array.new(old_table.size * 2) | |
rehash(old_table) | |
end | |
def rehash(old_table) | |
for e in old_table | |
self[e.key] = e.value if e | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment