'How to get Priority of C# PriorityQueue element
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.
Solution 1:[1]
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);
}
}
Solution 2:[2]
You can use any of the two methods as per your needs
TryPeek - if you want to get the value and the priority value without Poping out of the queue.
This method returns false - if the queue is empty otherwise true
myHeap.TryPeek(out TElement element, out TPriority priority)
myHeap.TryPeek(out int val, out int priorityval); //for int type
TryDequeue - If you want to Pop the value along with the priority value.
This method returns false - if the queue is empty otherwise true
myHeap.TryDequeue(out TElement element, out TPriority priority)
myHeap.TryDequeue(out int val, out int priorityval); // for int type
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 |