SimplePriorityQueue.cs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. namespace Priority_Queue
  5. {
  6. /// <summary>
  7. /// Credit: https://github.com/BlueRaja/High-Speed-Priority-Queue-for-C-Sharp
  8. /// A simplified priority queue implementation. Is stable, auto-resizes, and thread-safe, at the cost of being slightly slower than
  9. /// FastPriorityQueue
  10. /// </summary>
  11. /// <typeparam name="TItem">The type to enqueue</typeparam>
  12. /// <typeparam name="TPriority">The priority-type to use for nodes. Must extend IComparable&lt;TPriority&gt;</typeparam>
  13. public class SimplePriorityQueue<TItem, TPriority> : IPriorityQueue<TItem, TPriority>
  14. where TPriority : IComparable<TPriority>
  15. {
  16. private class SimpleNode : GenericPriorityQueueNode<TPriority>
  17. {
  18. public TItem Data { get; private set; }
  19. public SimpleNode(TItem data)
  20. {
  21. Data = data;
  22. }
  23. }
  24. private const int INITIAL_QUEUE_SIZE = 10;
  25. private readonly GenericPriorityQueue<SimpleNode, TPriority> _queue;
  26. public SimplePriorityQueue()
  27. {
  28. _queue = new GenericPriorityQueue<SimpleNode, TPriority>(INITIAL_QUEUE_SIZE);
  29. }
  30. /// <summary>
  31. /// Given an item of type T, returns the exist SimpleNode in the queue
  32. /// </summary>
  33. private SimpleNode GetExistingNode(TItem item)
  34. {
  35. var comparer = EqualityComparer<TItem>.Default;
  36. foreach (var node in _queue)
  37. {
  38. if (comparer.Equals(node.Data, item))
  39. {
  40. return node;
  41. }
  42. }
  43. throw new InvalidOperationException("Item cannot be found in queue: " + item);
  44. }
  45. /// <summary>
  46. /// Returns the number of nodes in the queue.
  47. /// O(1)
  48. /// </summary>
  49. public int Count
  50. {
  51. get
  52. {
  53. lock (_queue)
  54. {
  55. return _queue.Count;
  56. }
  57. }
  58. }
  59. /// <summary>
  60. /// Returns the head of the queue, without removing it (use Dequeue() for that).
  61. /// Throws an exception when the queue is empty.
  62. /// O(1)
  63. /// </summary>
  64. public TItem First
  65. {
  66. get
  67. {
  68. lock (_queue)
  69. {
  70. if (_queue.Count <= 0)
  71. {
  72. throw new InvalidOperationException("Cannot call .First on an empty queue");
  73. }
  74. SimpleNode first = _queue.First;
  75. return (first != null ? first.Data : default(TItem));
  76. }
  77. }
  78. }
  79. /// <summary>
  80. /// Removes every node from the queue.
  81. /// O(n)
  82. /// </summary>
  83. public void Clear()
  84. {
  85. lock (_queue)
  86. {
  87. _queue.Clear();
  88. }
  89. }
  90. /// <summary>
  91. /// Returns whether the given item is in the queue.
  92. /// O(n)
  93. /// </summary>
  94. public bool Contains(TItem item)
  95. {
  96. lock (_queue)
  97. {
  98. var comparer = EqualityComparer<TItem>.Default;
  99. foreach (var node in _queue)
  100. {
  101. if (comparer.Equals(node.Data, item))
  102. {
  103. return true;
  104. }
  105. }
  106. return false;
  107. }
  108. }
  109. /// <summary>
  110. /// Removes the head of the queue (node with minimum priority; ties are broken by order of insertion), and returns it.
  111. /// If queue is empty, throws an exception
  112. /// O(log n)
  113. /// </summary>
  114. public bool TryDequeue(out TItem item)
  115. {
  116. lock (_queue)
  117. {
  118. if (_queue.Count <= 0)
  119. {
  120. item = default(TItem);
  121. return false;
  122. }
  123. if (_queue.TryDequeue(out SimpleNode node))
  124. {
  125. item = node.Data;
  126. return true;
  127. }
  128. item = default(TItem);
  129. return false;
  130. }
  131. }
  132. /// <summary>
  133. /// Enqueue a node to the priority queue. Lower values are placed in front. Ties are broken by first-in-first-out.
  134. /// This queue automatically resizes itself, so there's no concern of the queue becoming 'full'.
  135. /// Duplicates are allowed.
  136. /// O(log n)
  137. /// </summary>
  138. public void Enqueue(TItem item, TPriority priority)
  139. {
  140. lock (_queue)
  141. {
  142. var node = new SimpleNode(item);
  143. if (_queue.Count == _queue.MaxSize)
  144. {
  145. _queue.Resize(_queue.MaxSize * 2 + 1);
  146. }
  147. _queue.Enqueue(node, priority);
  148. }
  149. }
  150. /// <summary>
  151. /// Removes an item from the queue. The item does not need to be the head of the queue.
  152. /// If the item is not in the queue, an exception is thrown. If unsure, check Contains() first.
  153. /// If multiple copies of the item are enqueued, only the first one is removed.
  154. /// O(n)
  155. /// </summary>
  156. public void Remove(TItem item)
  157. {
  158. lock (_queue)
  159. {
  160. try
  161. {
  162. _queue.Remove(GetExistingNode(item));
  163. }
  164. catch (InvalidOperationException ex)
  165. {
  166. throw new InvalidOperationException("Cannot call Remove() on a node which is not enqueued: " + item, ex);
  167. }
  168. }
  169. }
  170. /// <summary>
  171. /// Call this method to change the priority of an item.
  172. /// Calling this method on a item not in the queue will throw an exception.
  173. /// If the item is enqueued multiple times, only the first one will be updated.
  174. /// (If your requirements are complex enough that you need to enqueue the same item multiple times <i>and</i> be able
  175. /// to update all of them, please wrap your items in a wrapper class so they can be distinguished).
  176. /// O(n)
  177. /// </summary>
  178. public void UpdatePriority(TItem item, TPriority priority)
  179. {
  180. lock (_queue)
  181. {
  182. try
  183. {
  184. SimpleNode updateMe = GetExistingNode(item);
  185. _queue.UpdatePriority(updateMe, priority);
  186. }
  187. catch (InvalidOperationException ex)
  188. {
  189. throw new InvalidOperationException("Cannot call UpdatePriority() on a node which is not enqueued: " + item, ex);
  190. }
  191. }
  192. }
  193. public IEnumerator<TItem> GetEnumerator()
  194. {
  195. var queueData = new List<TItem>();
  196. lock (_queue)
  197. {
  198. //Copy to a separate list because we don't want to 'yield return' inside a lock
  199. foreach (var node in _queue)
  200. {
  201. queueData.Add(node.Data);
  202. }
  203. }
  204. return queueData.GetEnumerator();
  205. }
  206. IEnumerator IEnumerable.GetEnumerator()
  207. {
  208. return GetEnumerator();
  209. }
  210. public bool IsValidQueue()
  211. {
  212. lock (_queue)
  213. {
  214. return _queue.IsValidQueue();
  215. }
  216. }
  217. }
  218. /// <summary>
  219. /// A simplified priority queue implementation. Is stable, auto-resizes, and thread-safe, at the cost of being slightly slower than
  220. /// FastPriorityQueue
  221. /// This class is kept here for backwards compatibility. It's recommended you use Simple
  222. /// </summary>
  223. /// <typeparam name="TItem">The type to enqueue</typeparam>
  224. public class SimplePriorityQueue<TItem> : SimplePriorityQueue<TItem, float> { }
  225. }