Created
July 15, 2013 21:15
-
-
Save michel/6003579 to your computer and use it in GitHub Desktop.
TDD hashtable
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
require 'rspec' | |
#http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx | |
class String | |
def hashKey | |
rot_hash | |
end | |
#add hash | |
def add_key | |
key = 0 | |
size.times do |i| | |
key ^= self[i].ord | |
end | |
key | |
end | |
def xor_hash | |
key = 0 | |
size.times do |i| | |
key ^= self[i].ord | |
end | |
key | |
end | |
def xor_hash | |
key = 0 | |
size.times do |i| | |
key ^= self[i].ord | |
end | |
key | |
end | |
def rot_hash | |
key = 0 | |
size.times do |i| | |
key = ( key << 4 ) ^ ( key >> 28) ^ self[i].ord | |
end | |
key | |
end | |
end | |
class HashTable | |
def initialize(store_size=100) | |
@store_size = store_size | |
@store = Array.new(store_size) | |
end | |
def put(key,value) | |
@store[key_in_range(key)] = value | |
end | |
def get(key) | |
@store[key_in_range(key)] | |
end | |
def key_in_range(key) | |
key.hashKey % @store_size | |
end | |
end | |
describe 'Hashing' do | |
it "string key maps to a int" do | |
"hello".hashKey.class.should eql Fixnum | |
end | |
it 'is different for each sting you give it' do | |
'hello'.hashKey.should_not == 'hellx'.hashKey | |
end | |
it 'should be the same for every key you give it' do | |
'hello'.hashKey.should == 'hello'.hashKey | |
end | |
#it 'will have collisions with since the aloritm sucks' do | |
#'abs'.hashKey.should eql 'asb'.hashKey | |
#end | |
end | |
describe HashTable do | |
let(:table) { HashTable.new } | |
it ' allows you to put an object in the table with a sting key' do | |
table.put('key','object') | |
end | |
it 'allows you to get a value out of the table with a given key' do | |
table.put('key','object') | |
table.get('key').should eql('object') | |
end | |
it 'should return nil if key is not filled' do | |
table.get('nothere').should eql nil | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment