Repository navigation
Expand file tree
/
Copy pathhash_table.go
More file actions
110 lines (95 loc) · 1.99 KB
/
Copy pathhash_table.go
File metadata and controls
110 lines (95 loc) · 1.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package hashtable
import "hash/fnv"
type Entry[T comparable] struct {
key string
value T
}
type HashTable[T comparable] struct {
size int
count int
table [][]Entry[T]
}
func Constructor[T comparable] () *HashTable[T] {
size := 10
count := 0
table := make([][]Entry[T], size)
return &HashTable[T]{
size: size,
count: count,
table: table,
}
}
func (ht *HashTable[T]) hash (key string ) int {
h:=fnv.New32()
h.Write([]byte(key))
return int(h.Sum32()) % ht.size
}
func (ht *HashTable[T]) resize (newSize int) {
oldTable := ht.table
ht.table = make([][]Entry[T], newSize)
ht.size = newSize
ht.count = 0
for _, bucket := range oldTable {
if len(bucket) == 0 {
continue
}
for _, node := range bucket {
ht.Put(node.key, node.value)
}
}
}
func (ht *HashTable[T]) Put (key string, value T) {
index := ht.hash(key)
bucket:=ht.table[index]
if len(bucket) == 0 {
ht.table[index] = make([]Entry[T], 0)
}
for i, node := range bucket {
if node.key == key {
bucket[i].value = value
return
}
}
ht.table[index] = append(ht.table[index], Entry[T]{key: key, value: value})
ht.count++
if float64(ht.count) > float64(ht.size) * 0.7 {
ht.resize(ht.size * 2)
}
}
func (ht *HashTable[T]) Get (key string) (T, bool) {
index := ht.hash(key)
bucket:=ht.table[index]
if len(bucket) == 0 {
return *new(T), false
}
for _, node := range bucket {
if node.key == key {
return node.value, true
}
}
return *new(T), false
}
func (ht *HashTable[T]) Remove (key string) (T, bool) {
index := ht.hash(key)
bucket:=ht.table[index]
if len(bucket) == 0 {
return *new(T), false
}
for i, node := range bucket {
if node.key == key {
ht.table[index] = append(ht.table[index][:i], ht.table[index][i+1:]...)
ht.count--
if float64(ht.count) < float64(ht.size) * 0.2 {
ht.resize(ht.size / 2)
}
return node.value, true
}
}
return *new(T), false
}
func (ht *HashTable[T]) Count () int {
return ht.count
}
func (ht *HashTable[T]) Size () int {
return ht.size
}