From 667ee8338b5ab55f9024173787cd4f949e9dfd3c Mon Sep 17 00:00:00 2001 From: Matthew Kim <38759997+friendlymatthew@users.noreply.github.com> Date: Mon, 3 Jun 2024 11:25:27 -0400 Subject: [PATCH] feat: from base queue (#321) --- pkg/hnsw/pq.go | 10 ++++++++++ pkg/hnsw/pq_test.go | 44 ++++++++++++++++++++++---------------------- 2 files changed, 32 insertions(+), 22 deletions(-) diff --git a/pkg/hnsw/pq.go b/pkg/hnsw/pq.go index 96dfd04..7eb21cd 100644 --- a/pkg/hnsw/pq.go +++ b/pkg/hnsw/pq.go @@ -149,3 +149,13 @@ func (bq *BaseQueue) update(item *Item, id Id, dist float32) { item.dist = dist heap.Fix(bq, item.index) } + +func FromBaseQueue(bq *BaseQueue, comparator Comparator) *BaseQueue { + newBq := NewBaseQueue(comparator) + + for _, item := range bq.items { + newBq.Insert(item.id, item.dist) + } + + return newBq +} diff --git a/pkg/hnsw/pq_test.go b/pkg/hnsw/pq_test.go index bce3413..c98e223 100644 --- a/pkg/hnsw/pq_test.go +++ b/pkg/hnsw/pq_test.go @@ -45,7 +45,29 @@ func TestPQ(t *testing.T) { t.Errorf("got %d, want %d", res, c.expected) } } + }) + + t.Run("interchange", func(t *testing.T) { + bq := NewBaseQueue(MinComparator{}) + for i := 0; i < 100; i++ { + bq.Insert(Id(i), float32(i)) + } + + incBq := FromBaseQueue(bq, MaxComparator{}) + + i := Id(99) + for !incBq.IsEmpty() { + item, err := incBq.Peel() + if err != nil { + t.Fatal(err) + } + if item.id != i { + t.Fatalf("got %d, want %d", item.id, i) + } + + i -= 1 + } }) } @@ -81,25 +103,3 @@ func furthestBuildings(heights []int, bricks, ladders int) (int, error) { return len(heights) - 1, nil } - -/* - - - - - - - - - - - - - - - - - - - - */