Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would you obtain the first and last items in a Queue?

Say I have a rolling collection of values where I specify the size of the collection and any time a new value is added, any old values beyond this specified size are dropped off. Obviously (and I've tested this) the best type of collection to use for this behavior is a Queue:

myQueue.Enqueue(newValue)
If myQueue.Count > specifiedSize Then myQueue.Dequeue()

However, what if I want to calculate the difference between the first and last items in the Queue? Obviously I can't access the items by index. But to switch from a Queue to something implementing IList seems like overkill, as does writing a new Queue-like class. Right now I've got:

Dim firstValue As Integer = myQueue.Peek()
Dim lastValue As Integer = myQueue.ToArray()(myQueue.Count - 1)
Dim diff As Integer = lastValue - firstValue

That call to ToArray() bothers me, but a superior alternative isn't coming to me. Any suggestions?

like image 558
Dan Tao Avatar asked Aug 20 '09 19:08

Dan Tao


2 Answers

One thing you could do is have a temporary variable that stores the value that was just enqueued because that will be the last value and so the variable can be accessed to get that value.

like image 90
murgatroid99 Avatar answered Oct 18 '22 14:10

murgatroid99


public class LastQ<T> : Queue<T>
{
    public T Last { get; private set; }

    public new void Enqueue(T item)
    {
         Last = item;
         base.Enqueue(item);
    }
}

Edit: Obviously this basic class should be more robust to do things like protect the Last property on an empty queue. But this should be enough for the basic idea.

like image 43
xanadont Avatar answered Oct 18 '22 15:10

xanadont