Skip to content

Commit 697fe1b

Browse files
committed
Mitigate collisions on hash table (Ruby)
1 parent 109ded3 commit 697fe1b

File tree

1 file changed

+13
-9
lines changed

1 file changed

+13
-9
lines changed

src/ruby/hash_table.rb

+13-9
Original file line numberDiff line numberDiff line change
@@ -4,18 +4,22 @@ class HashTable
44
attr_reader :hash
55

66
def initialize(size = 500)
7-
@hash = Array.new
7+
@hash = Array.new(size) { [] }
88
@size = size
99
end
1010

1111
def put(key, value)
1212
idx = calculate_hash(key)
13-
@hash[idx] = value
13+
@hash[idx] << [key, value]
1414
end
1515

1616
def get(key)
1717
idx = calculate_hash(key)
18-
@hash[idx]
18+
19+
bucket = @hash[idx]
20+
pair = bucket.find { |pair| pair[0] == key }
21+
22+
pair[1] if pair
1923
end
2024

2125
def delete(key)
@@ -31,11 +35,11 @@ def calculate_hash(str)
3135
end
3236

3337
hash = HashTable.new
34-
hash.put(:name, "Jane")
35-
hash.put(:age, 22)
38+
hash.put(:code, "ABC123")
39+
hash.put(:mode, "dark")
3640

37-
puts hash.get(:name) # => Jane
38-
puts hash.get(:age) # => 22
41+
puts "Code is #{hash.get(:code)}" # => ABC123
42+
puts "Mode is #{hash.get(:mode)}" # => "dark
3943

40-
hash.delete(:name)
41-
puts hash.get(:name) # => nil
44+
hash.delete(:code)
45+
puts hash.get(:code) # => nil

0 commit comments

Comments
 (0)