I am initializing a priority queue that stores XY coordinates, prioritized by their euclidian distance from origin. I created a custom Comparer
that makes this operate as a max heap:
PriorityQueue<int[], double> maxHeap = new PriorityQueue<int[], double>(Comparer<double>.Create((x, y) => x.CompareTo(y)));
This works great, except sometimes I want to be able to look at the top of the heap using Peek()
. I can get the value of the element, the point which has type int[]
, but I can't get the priority. I don't see anything that would allow me to access TPriority
. Take this use case for example, which is a common usage of heaps to get the top/bottom K elements in a collection:
for (int i = k; i < points.Length; i++)
{
double euclidianDistance = EuclidianDistance(points[i]);
if (euclidianDistance < EuclidianDistance(maxHeap.Peek()))
{
maxHeap.Dequeue();
maxHeap.Enqueue(points[i], euclidianDistance);
}
}
You will see that I have to compute the euclidian distance again for the element at the top of the heap. Visual Studio shows me this, although I cannot seem to access that second property of type double which refers to the priority.
I figured out that this requires usage of a try/get:
for (int i = k; i < points.Length; i++)
{
double euclidianDistance = EuclidianDistance(points[i]);
if (maxHeap.TryPeek(out int[] topPoint, out double priority) && euclidianDistance < priority)
{
maxHeap.Dequeue();
maxHeap.Enqueue(points[i], euclidianDistance);
}
}