Adds in neighbour implementation implemented and running. Behaviour not tested yet.

This commit is contained in:
Julien Lengrand-Lambert
2013-11-24 16:54:43 +01:00
parent 96d3c8ca00
commit 70d268983b
2 changed files with 36 additions and 10 deletions

View File

@@ -114,7 +114,7 @@ class HMTableCollision(HashMap):
return h % self._hash_size return h % self._hash_size
class HashMapNeighbourCollision(): class HMNeighbourCollision():
def __init__(self, hash_size=513): def __init__(self, hash_size=513):
self._hash_size = hash_size self._hash_size = hash_size
self._size = 0 self._size = 0
@@ -126,20 +126,39 @@ class HashMapNeighbourCollision():
Raises an Exception if a collision is detected Raises an Exception if a collision is detected
""" """
my_key = self._hash(key) my_key = self._hash(key)
if self.hmap[my_key] == None: idx = self._find_free_idx(my_key)
self.hmap[my_key] = value
self._size += 1 self.hmap[idx] = value
else: self._size += 1
raise Exception("Collision detected at index %d", key)
def _find_free_idx(self, key):
"""
Given an index in the current hash table, finds the nearest
element with a free value
"""
idx = key
cur_ptr = 1
negative = True
while(True):
if self.hmap[idx] == None:
return idx
else:
if negative:
idx = key - cur_ptr
negative = False
else:
idx = key + cur_ptr
negative = True
cur_ptr += 1
def get(self, key): def get(self, key):
""" """
Finds the element in the hash table that may contain the id for Finds the element in the hash table that may contain the id for
the string we are looking for the string we are looking for
""" """
my_key = self._hash(key) #TODO
return self.hmap[my_key]
def size(self): def size(self):
return self._size return self._size

View File

@@ -6,13 +6,20 @@ Unit tests for the Hash Map table implementation
from hm import HashMap from hm import HashMap
from hm import HMTableCollision from hm import HMTableCollision
from hm import HMNeighbourCollision
import unittest import unittest
class test_hash_map_neighbour_collision(unittest.TestCase): class test_hash_map_neighbour_collision(unittest.TestCase):
def test_add(self): def test_add(self):
pass hm = HMNeighbourCollision()
hm.add("One", "Ibiza")
self.assertEqual(hm.size(), 1)
hm.add("One", "Ibiza2")
self.assertEqual(hm.size(), 2)
class test_hash_map_table_collision(unittest.TestCase): class test_hash_map_table_collision(unittest.TestCase):