Skip to content

Commit

Permalink
feat: clone
Browse files Browse the repository at this point in the history
  • Loading branch information
friendlymatthew committed Jul 8, 2024
1 parent f6abe6a commit 6017a80
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
17 changes: 17 additions & 0 deletions pkg/hnsw/heap.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,23 @@ func NewDistHeap() *DistHeap {
return d
}

func (d *DistHeap) Clone() *DistHeap {
n := &DistHeap{
items: make([]*Item, len(d.items)),
visited: make(map[Id]int, len(d.visited)),
}

for i, item := range d.items {
n.items[i] = &*item
}

for id, index := range d.visited {
n.visited[id] = index
}

return n
}

func (d *DistHeap) PeekMinItem() (*Item, error) {
if d.IsEmpty() {
return nil, EmptyHeapError
Expand Down
33 changes: 32 additions & 1 deletion pkg/hnsw/heap_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package hnsw

import "testing"
import (
"reflect"
"testing"
)

func TestHeap(t *testing.T) {

Expand Down Expand Up @@ -138,6 +141,34 @@ func TestHeap(t *testing.T) {
}
}
})

t.Run("copy", func(t *testing.T) {
m := NewDistHeap()

for i := 0; i <= 10; i++ {
m.Insert(Id(i), float32(10-i))
}

n := m.Clone()

reflect.DeepEqual(m.items, n.items)
reflect.DeepEqual(m.visited, n.visited)

expectedId := Id(10)

for !n.IsEmpty() {
item, err := n.PopMinItem()
if err != nil {
return
}

if item.id != expectedId {
t.Fatalf("expected id to be %v, got %v", expectedId, item.id)
}

expectedId -= 1
}
})
}

func furthestBuildings(heights []int, bricks, ladders int) (int, error) {
Expand Down

0 comments on commit 6017a80

Please sign in to comment.