Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Hash it out #140

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion 01-data-structures/04-hashes-part-1/hash_item.rb
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
class HashItem
attr_accessor :key
attr_accessor :value

def initialize(key, value)
@key, @value = key, value
end
end
20 changes: 20 additions & 0 deletions 01-data-structures/04-hashes-part-1/hashclass.rb
Original file line number Diff line number Diff line change
@@ -1,27 +1,47 @@
require_relative 'hash_item'

class HashClass

def initialize(size)
@items = Array.new(size)
end

def []=(key, value)
item = HashItem.new(key, value)
i = index(key, size)

if @items[i].nil?
@items[i] = item
elsif @items[i].key != item.key
self.resize
self[key] = value
elsif @items[i].value != item.value
self.resize
@items[index(item.key, size)] = value
end
end


def [](key)
@items[self.index(key, self.size)].value
end

def resize
old_items = @items.compact
@items = Array.new(self.size * 2)
old_items.each { |item| self[item.key] = item.value }
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.each_byte.sum % size
end

# Simple method to return the number of items in the hash
def size
@items.length
end

end
1 change: 1 addition & 0 deletions 01-data-structures/04-hashes-part-1/hashes-1-answers.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Doubling the size of the underlying array of my HashClass may be a poor idea because it'll increase the open slots in the array exponentially which may lead to more fragmentation. Doubling the size is also a slow process. Using prime numbers to resize is better as that'll reduce the number of collisions.