Created
November 24, 2016 18:16
-
-
Save ignacy/fa7fa6781dae1291978f0d5f1049cc78 to your computer and use it in GitHub Desktop.
Hash table with chaining for collision resolution
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
package hash_table | |
type Node struct { | |
key string | |
value int | |
next *Node | |
} | |
// HashTable implements hash table with chaining as colision | |
// resolution technique | |
type HashTable struct { | |
size int | |
nodes []Node | |
} | |
func NewHashTable(size int) *HashTable { | |
return &HashTable{ | |
size, | |
make([]Node, size), | |
} | |
} | |
func (ht *HashTable) Put(key string, value int) { | |
index := hashFunction(key, ht.size) | |
node := ht.nodes[index] | |
n := findInLinkedList(&node, key) | |
if n == nil { | |
n = findLast(&node) | |
} | |
n.next = &Node{key, value, nil} | |
ht.nodes[index] = node | |
} | |
func (ht *HashTable) Get(key string) int { | |
index := hashFunction(key, ht.size) | |
n := findInLinkedList(&ht.nodes[index], key) | |
if n == nil { | |
return 0 | |
} | |
return n.value | |
} | |
func findInLinkedList(node *Node, key string) *Node { | |
if node.key == key { | |
return node | |
} | |
if node.next == nil { | |
return nil | |
} | |
return findInLinkedList(node.next, key) | |
} | |
func findLast(node *Node) *Node { | |
if node.next == nil { | |
return node | |
} | |
return findLast(node.next) | |
} | |
func hashFunction(key string, places int) int { | |
sum := 0 | |
for _, c := range key { | |
sum += int(c - '0') | |
} | |
return sum % places | |
} |
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
package hash_table | |
import "testing" | |
var hashTableTests = []struct { | |
key string | |
value int | |
}{ | |
{"ala", 10}, | |
{"bla", 20}, | |
{"laa", 30}, | |
{"alb", 40}, | |
{"abl", 50}, | |
} | |
func TestSettingHashTableElementsParser(t *testing.T) { | |
myTable := NewHashTable(10) | |
for _, tt := range hashTableTests { | |
myTable.Put(tt.key, tt.value) | |
} | |
for _, tt := range hashTableTests { | |
if s := myTable.Get(tt.key); s != tt.value { | |
t.Errorf("GOT %d, WANT %d", s, tt.value) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment