-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
154 lines (122 loc) · 2.42 KB
/
main.go
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
package main
import "fmt"
type Node struct {
key int
value string
next *Node
}
// HashMap with chaining
type HashMap struct {
buckets []*Node
size int
}
func NewHashMap(size int) *HashMap {
return &HashMap{
buckets: make([]*Node, size),
size: size,
}
}
func (hm *HashMap) hashFunction(key int) int {
return key % hm.size
}
func (hm *HashMap) Insert(key int, value string) {
index := hm.hashFunction(key)
head := hm.buckets[index]
for head != nil {
if head.key == key {
head.value = value
return
}
head = head.next
}
newNode := &Node{
key: key,
value: value,
next: hm.buckets[index],
}
hm.buckets[index] = newNode
}
func (hm *HashMap) Get(key int) (string, bool) {
index := hm.hashFunction(key)
head := hm.buckets[index]
for head != nil {
if head.key == key {
return head.value, true
}
head = head.next
}
return "", false
}
func (hm *HashMap) Delete(key int) bool {
index := hm.hashFunction(key)
head := hm.buckets[index]
if head == nil {
return false
}
if head.key == key {
hm.buckets[index] = head.next
return true
}
prev := head
for head != nil {
if head.key == key {
prev.next = head.next
return true
}
prev = head
head = head.next
}
return false
}
func (hm *HashMap) ReHash() {
newSize := hm.size * 2
newBuckets := make([]*Node, newSize)
for _, bucket := range hm.buckets {
node := bucket
for node != nil {
newIndex := node.key % newSize
newNode := &Node{key: node.key, value: node.value, next: newBuckets[newIndex]}
newBuckets[newIndex] = newNode
node = node.next
}
}
hm.buckets = newBuckets
hm.size = newSize
}
// PrintHashMap prints the contents of the hash map
func (hm *HashMap) PrintHashMap() {
for i, node := range hm.buckets {
fmt.Printf("Bucket %d: ", i)
for node != nil {
fmt.Printf("(%d, %s) -> ", node.key, node.value)
node = node.next
}
fmt.Println("nil")
}
}
func main() {
hm := NewHashMap(10)
hm.Insert(10, "A")
hm.Insert(20, "B")
hm.Insert(30, "C")
hm.Insert(11, "D")
hm.PrintHashMap()
value, found := hm.Get(20)
if found {
fmt.Println("Found Value: ", value)
} else {
fmt.Println("Value not found")
}
isDeleted := hm.Delete(20)
if !isDeleted {
fmt.Println("Error deleting Value")
} else {
fmt.Println("Key deleted.")
}
hm.PrintHashMap()
hm.ReHash()
hm.PrintHashMap()
}
/**
Load factor: Number of elements in the table / Size of the table ( number of buckets )
*/