Вопрос

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());
}

Другие советы

I would do something like this:

public static void TrimPQueue(PriorityQueue<int> paraQueue, int newSize)
{
    if (newSize >= paraQueue.Count)
        return ;
    for (int i = 1; i < newSize + 1; i++)
        paraQueue.Dequeue();
} 

Because you don't have to make a copy if you are still changing the current queue.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top