summaryrefslogtreecommitdiff
path: root/search
diff options
context:
space:
mode:
authorPaul Buetow <git@mx.buetow.org>2020-12-26 09:20:57 +0000
committerPaul Buetow <git@mx.buetow.org>2020-12-26 09:20:57 +0000
commitc8e24d8da9ed313566e4c2a71c11452246e4d171 (patch)
tree961fc9749f136d52c03f39d71b301bdc074fc70e /search
parent364087d3b4b2b1e6f809921c931a7654a725ebee (diff)
hash works
Diffstat (limited to 'search')
-rw-r--r--search/hash.go91
1 files changed, 33 insertions, 58 deletions
diff --git a/search/hash.go b/search/hash.go
index 7611008..717a825 100644
--- a/search/hash.go
+++ b/search/hash.go
@@ -1,88 +1,63 @@
package search
-type HashElem struct {
- key int
- val int
- next *HashElem
-}
-
type Hash struct {
- root *HashElem
- size int
+ buckets []*Elementary
+ capacity int
+ size int
}
-func NewHash() *Hash {
- return &Hash{}
+func NewHash(capacity int) *Hash {
+ return &Hash{
+ buckets: make([]*Elementary, capacity),
+ capacity: capacity,
+ }
}
func (h *Hash) Empty() bool {
- return s.root == nil
+ return h.Size() == 0
}
func (h *Hash) Size() int {
- return s.size
+ return h.size
}
-func (h *Hash) Put(key int, val int) {
- if s.Empty() {
- s.root = &HashElem{key, val, nil}
- s.size++
- return
+func (h *Hash) hash(key int) int {
+ i := key + key*2 + key<<10 + key>>2
+ if i < 0 {
+ i = -i
}
+ return i % h.capacity
+}
- elem := s.root
+func (h *Hash) Put(key int, val int) {
+ i := h.hash(key)
- for {
- if elem.key == key {
- elem.val = val
- return
- }
- if elem.next == nil {
- elem.next = &HashElem{key, val, nil}
- s.size++
- return
- }
- elem = elem.next
+ if h.buckets[i] == nil {
+ elem := NewElementary()
+ elem.Put(key, val)
+ h.buckets[i] = elem
+ return
}
+
+ h.buckets[i].Put(key, val)
}
func (h *Hash) Get(key int) (int, error) {
- elem := s.root
+ i := h.hash(key)
- for elem != nil {
- if elem.key == key {
- return elem.val, nil
- }
- elem = elem.next
+ 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) {
- if s.Empty() {
- return 0, NotFound
- }
-
- if s.root.key == key {
- defer func() {
- s.root = s.root.next
- }()
- s.size--
- return s.root.val, nil
- }
+ i := h.hash(key)
- elem := s.root
- for elem.next != nil {
- if elem.next.key == key {
- defer func() {
- elem.next = elem.next.next
- }()
- s.size--
- return elem.next.val, nil
- }
- elem = elem.next
+ if h.buckets[i] == nil {
+ return -1, NotFound
}
- return 0, NotFound
+ return h.buckets[i].Del(key)
}