Requirement: I have a Max-Priority Queue with n elements. Now I want to keep only the m-maximum elements (where m<=n) and drop the rest from the queue. In other words, I want to trim the queue.
How do I achieve this?
One way that I could come up with is, dequeue m elements and put them into another queue. Then assign the reference of the new queue into that of the old queue.
public static PriorityQueue<int> TrimPQueue(PriorityQueue<int> paraQueue, int newSize)
{
if (newSize >= paraQueue.Count)
return paraQueue;
PriorityQueue<int> newQueue = new PriorityQueue<int>(PriorityQueueType.Maximum);
for (int i = 1; i < newSize + 1; i++)
{
int temp = paraQueue.Dequeue();
newQueue.Add(temp);
}
return newQueue;
}
Isn't there a better way to do this? I would prefer if there's a way to trim the working-queue, without having to create a new queue-object.
The PriorityQueue implements the IEnumerable interface so you could use that in combination with the Linq extension method Last():
while (paraQueue.Count > newSize)
{
paraQueue.Remove(paraQueue.Last());
}