| | | 1 | | using System.Collections; |
| | | 2 | | using System.Collections.Generic; |
| | | 3 | | using System.Linq; |
| | | 4 | | |
| | | 5 | | // The priority queue dequeues elements in order of increasing priority. |
| | | 6 | | public class PriorityQueue<T> : IEnumerable<T> { |
| | | 7 | | // Buffer containing the data. |
| | 0 | 8 | | private SortedDictionary<float, Queue<T>> _buffer = new SortedDictionary<float, Queue<T>>(); |
| | | 9 | | |
| | | 10 | | // Return whether the priority queue is empty. |
| | 77 | 11 | | public bool IsEmpty() { |
| | 77 | 12 | | return _buffer.Count == 0; |
| | 77 | 13 | | } |
| | | 14 | | |
| | | 15 | | // Remove all queued items. |
| | 23 | 16 | | public void Clear() { |
| | 23 | 17 | | _buffer.Clear(); |
| | 23 | 18 | | } |
| | | 19 | | |
| | | 20 | | // Enqueue an item. |
| | 0 | 21 | | public void Enqueue(T item, float priority) { |
| | 0 | 22 | | if (!_buffer.ContainsKey(priority)) { |
| | 0 | 23 | | _buffer[priority] = new Queue<T>(); |
| | 0 | 24 | | } |
| | 0 | 25 | | _buffer[priority].Enqueue(item); |
| | 0 | 26 | | } |
| | | 27 | | |
| | | 28 | | // Dequeue the item with the lowest priority value. |
| | 0 | 29 | | public T Dequeue() { |
| | 0 | 30 | | if (IsEmpty()) { |
| | 0 | 31 | | throw new System.InvalidOperationException("The priority queue is empty."); |
| | | 32 | | } |
| | | 33 | | |
| | 0 | 34 | | var firstPair = _buffer.First(); |
| | 0 | 35 | | Queue<T> queue = firstPair.Value; |
| | 0 | 36 | | T item = queue.Dequeue(); |
| | 0 | 37 | | if (queue.Count == 0) { |
| | 0 | 38 | | _buffer.Remove(firstPair.Key); |
| | 0 | 39 | | } |
| | 0 | 40 | | return item; |
| | 0 | 41 | | } |
| | | 42 | | |
| | | 43 | | // Peek the item with the lowest priority value. |
| | 0 | 44 | | public T Peek() { |
| | 0 | 45 | | if (IsEmpty()) { |
| | 0 | 46 | | throw new System.InvalidOperationException("The priority queue is empty."); |
| | | 47 | | } |
| | 0 | 48 | | return _buffer.First().Value.Peek(); |
| | 0 | 49 | | } |
| | | 50 | | |
| | | 51 | | // Return an enumerator for the priority queue. |
| | 0 | 52 | | public IEnumerator<T> GetEnumerator() { |
| | 0 | 53 | | foreach (var pair in _buffer) { |
| | 0 | 54 | | foreach (var item in pair.Value) { |
| | 0 | 55 | | yield return item; |
| | 0 | 56 | | } |
| | 0 | 57 | | } |
| | 0 | 58 | | } |
| | 0 | 59 | | IEnumerator IEnumerable.GetEnumerator() { |
| | 0 | 60 | | return GetEnumerator(); |
| | 0 | 61 | | } |
| | | 62 | | } |