using System; using System.Collections.Generic; using System.Text; namespace DSDecmp { /// /// Very simplistic implementation of a priority queue that returns items with lowest priority first. /// This is not the most efficient implementation, but required the least work while using the classes /// from the .NET collections, and without requiring importing another dll or several more class files /// in order to make it work. /// /// The type of the priority values. /// The type of item to put into the queue. public class SimpleReversedPrioQueue { private SortedDictionary> items; private int itemCount; /// /// Gets the number of items in this queue. /// public int Count { get { return this.itemCount; } } /// /// Creates a new, empty reverse priority queue. /// public SimpleReversedPrioQueue() { this.items = new SortedDictionary>(); this.itemCount = 0; } /// /// Enqueues the given value, using the given priority. /// /// The priority of the value. /// The value to enqueue. public void Enqueue(TPrio priority, TValue value) { if (!this.items.ContainsKey(priority)) this.items.Add(priority, new LinkedList()); this.items[priority].AddLast(value); this.itemCount++; } /// /// Gets the current value with the lowest priority from this queue, without dequeueing the value. /// /// The priority of the returned value. /// The current value with the lowest priority. /// If there are no items left in this queue. public TValue Peek(out TPrio priority) { if (this.itemCount == 0) throw new IndexOutOfRangeException(); foreach (KeyValuePair> kvp in this.items) { priority = kvp.Key; return kvp.Value.First.Value; } throw new IndexOutOfRangeException(); } /// /// Dequeues the current value at the head of thisreverse priority queue. /// /// The priority of the dequeued value. /// The dequeued value, that used to be at the head of this queue. /// If this queue does not contain any items. public TValue Dequeue(out TPrio priority) { if (this.itemCount == 0) throw new IndexOutOfRangeException(); LinkedList lowestLL = null; priority = default(TPrio); foreach (KeyValuePair> kvp in this.items) { lowestLL = kvp.Value; priority = kvp.Key; break; } TValue returnValue = lowestLL.First.Value; lowestLL.RemoveFirst(); // remove unused linked lists. priorities will only grow. if (lowestLL.Count == 0) { this.items.Remove(priority); } this.itemCount--; return returnValue; } } }