diff --git a/01-data-structures/04-hashes-part-1/hash_item.rb b/01-data-structures/04-hashes-part-1/hash_item.rb index 4a420212..5953907a 100644 --- a/01-data-structures/04-hashes-part-1/hash_item.rb +++ b/01-data-structures/04-hashes-part-1/hash_item.rb @@ -3,5 +3,7 @@ class HashItem attr_accessor :value def initialize(key, value) + @key = key + @value = value end -end \ No newline at end of file +end diff --git a/01-data-structures/04-hashes-part-1/hashclass.rb b/01-data-structures/04-hashes-part-1/hashclass.rb index e538428a..11e79caa 100644 --- a/01-data-structures/04-hashes-part-1/hashclass.rb +++ b/01-data-structures/04-hashes-part-1/hashclass.rb @@ -1,3 +1,5 @@ +require_relative 'hash_item' + class HashClass def initialize(size) @@ -5,23 +7,50 @@ def initialize(size) end def []=(key, value) + i = index(key, size()) + new_item = @items[i] + if new_item == nil + @items[i] = HashItem.new(key,value) + elsif new_item.key != key + while @items[index(key, size())].key != nil && @items[index(key, size())].key != key + resize() + j = index(key, size()) + break if @items[j] == nil + end + self[key] = value + elsif new_item.key == key && new_item.value != value + resize() + new_item.value = value + end end def [](key) + i = index(key, size()) + @items[i].value end def resize + @size = @items.length * 2 + resized_hash = Array.new(@size) + @items.each do |item| + if item != nil + resized_hash[index(item.key, @size)] = item + end + end + @items = resized_hash end # Returns a unique, deterministically reproducible index into an array # We are hashing based on strings, let's use the ascii value of each string as # a starting point. def index(key, size) + key.sum % size end # Simple method to return the number of items in the hash def size + @items.length end -end \ No newline at end of file +end