summaryrefslogtreecommitdiff
path: root/search/hash.go
diff options
context:
space:
mode:
authorPaul Buetow <paul@buetow.org>2023-04-02 20:22:13 +0300
committerPaul Buetow <paul@buetow.org>2023-04-02 20:22:13 +0300
commit0c6d4ed2e499e3e17165e43803d0d1c6dd0956d9 (patch)
tree6d6a5df53d1dd3e655d24f0423f24bc52ad9784c /search/hash.go
parentf78ba2cdc6840dbc52a27a2f9fac28f3b61e8b7b (diff)
initial generics
Diffstat (limited to 'search/hash.go')
-rw-r--r--search/hash.go34
1 files changed, 19 insertions, 15 deletions
diff --git a/search/hash.go b/search/hash.go
index 717a825..0b41b6b 100644
--- a/search/hash.go
+++ b/search/hash.go
@@ -1,39 +1,43 @@
package search
-type Hash struct {
- buckets []*Elementary
+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(capacity int) *Hash {
- return &Hash{
- buckets: make([]*Elementary, capacity),
+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) Empty() bool {
+func (h *Hash[K,V]) Empty() bool {
return h.Size() == 0
}
-func (h *Hash) Size() int {
+func (h *Hash[K,V]) Size() int {
return h.size
}
-func (h *Hash) hash(key int) int {
+func (h *Hash[K,V]) hash(key K) int {
i := key + key*2 + key<<10 + key>>2
if i < 0 {
i = -i
}
- return i % h.capacity
+ return int(i) % h.capacity
}
-func (h *Hash) Put(key int, val int) {
+func (h *Hash[K,V]) Put(key K, val V) {
i := h.hash(key)
if h.buckets[i] == nil {
- elem := NewElementary()
+ elem := NewElementary[K,V]()
elem.Put(key, val)
h.buckets[i] = elem
return
@@ -42,21 +46,21 @@ func (h *Hash) Put(key int, val int) {
h.buckets[i].Put(key, val)
}
-func (h *Hash) Get(key int) (int, error) {
+func (h *Hash[K,V]) Get(key K) (V, error) {
i := h.hash(key)
if h.buckets[i] == nil {
- return -1, NotFound
+ return 0, NotFound
}
return h.buckets[i].Get(key)
}
-func (h *Hash) Del(key int) (int, error) {
+func (h *Hash[K,V]) Del(key K) (V, error) {
i := h.hash(key)
if h.buckets[i] == nil {
- return -1, NotFound
+ return 0, NotFound
}
return h.buckets[i].Del(key)