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

hashing function #146

Open
wants to merge 3 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
4 changes: 3 additions & 1 deletion 01-data-structures/04-hashes-part-1/hash_item.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,7 @@ class HashItem
attr_accessor :value

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

class HashClass

def initialize(size)
@items = Array.new(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
end