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
|
package search
import (
"codeberg.org/snonux/algorithms/ds"
)
type Hash[K ds.Integer,V ds.Number] struct {
buckets []*Elementary[K,V]
capacity int
size int
}
func NewHash[K ds.Integer,V ds.Number](capacity int) *Hash[K,V] {
return &Hash[K,V]{
buckets: make([]*Elementary[K,V], capacity),
capacity: capacity,
}
}
func (h *Hash[K,V]) Empty() bool {
return h.Size() == 0
}
func (h *Hash[K,V]) Size() int {
return h.size
}
func (h *Hash[K,V]) hash(key K) int {
i := key + key*2 + key<<10 + key>>2
if i < 0 {
i = -i
}
return int(i) % h.capacity
}
func (h *Hash[K,V]) Put(key K, val V) {
i := h.hash(key)
if h.buckets[i] == nil {
elem := NewElementary[K,V]()
elem.Put(key, val)
h.buckets[i] = elem
return
}
h.buckets[i].Put(key, val)
}
func (h *Hash[K,V]) Get(key K) (V, error) {
i := h.hash(key)
if h.buckets[i] == nil {
return 0, NotFound
}
return h.buckets[i].Get(key)
}
func (h *Hash[K,V]) Del(key K) (V, error) {
i := h.hash(key)
if h.buckets[i] == nil {
return 0, NotFound
}
return h.buckets[i].Del(key)
}
|