GenericPriorityQueue.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Runtime.CompilerServices;
  5. //TODO Fix namespace or replace
  6. namespace Priority_Queue
  7. {
  8. /// <summary>
  9. /// Credit: https://github.com/BlueRaja/High-Speed-Priority-Queue-for-C-Sharp
  10. /// A copy of StablePriorityQueue which also has generic priority-type
  11. /// </summary>
  12. /// <typeparam name="TItem">The values in the queue. Must extend the GenericPriorityQueue class</typeparam>
  13. /// <typeparam name="TPriority">The priority-type. Must extend IComparable&lt;TPriority&gt;</typeparam>
  14. public sealed class GenericPriorityQueue<TItem, TPriority> : IFixedSizePriorityQueue<TItem, TPriority>
  15. where TItem : GenericPriorityQueueNode<TPriority>
  16. where TPriority : IComparable<TPriority>
  17. {
  18. private int _numNodes;
  19. private TItem[] _nodes;
  20. private long _numNodesEverEnqueued;
  21. /// <summary>
  22. /// Instantiate a new Priority Queue
  23. /// </summary>
  24. /// <param name="maxNodes">The max nodes ever allowed to be enqueued (going over this will cause undefined behavior)</param>
  25. public GenericPriorityQueue(int maxNodes)
  26. {
  27. #if DEBUG
  28. if (maxNodes <= 0)
  29. {
  30. throw new InvalidOperationException("New queue size cannot be smaller than 1");
  31. }
  32. #endif
  33. _numNodes = 0;
  34. _nodes = new TItem[maxNodes + 1];
  35. _numNodesEverEnqueued = 0;
  36. }
  37. /// <summary>
  38. /// Returns the number of nodes in the queue.
  39. /// O(1)
  40. /// </summary>
  41. public int Count => _numNodes;
  42. /// <summary>
  43. /// Returns the maximum number of items that can be enqueued at once in this queue. Once you hit this number (ie. once Count == MaxSize),
  44. /// attempting to enqueue another item will cause undefined behavior. O(1)
  45. /// </summary>
  46. public int MaxSize => _nodes.Length - 1;
  47. /// <summary>
  48. /// Removes every node from the queue.
  49. /// O(n) (So, don't do this often!)
  50. /// </summary>
  51. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  52. public void Clear()
  53. {
  54. Array.Clear(_nodes, 1, _numNodes);
  55. _numNodes = 0;
  56. }
  57. /// <summary>
  58. /// Returns (in O(1)!) whether the given node is in the queue. O(1)
  59. /// </summary>
  60. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  61. public bool Contains(TItem node)
  62. {
  63. #if DEBUG
  64. if (node == null)
  65. {
  66. throw new ArgumentNullException(nameof(node));
  67. }
  68. if (node.QueueIndex < 0 || node.QueueIndex >= _nodes.Length)
  69. {
  70. throw new InvalidOperationException("node.QueueIndex has been corrupted. Did you change it manually? Or add this node to another queue?");
  71. }
  72. #endif
  73. return (_nodes[node.QueueIndex] == node);
  74. }
  75. /// <summary>
  76. /// Enqueue a node to the priority queue. Lower values are placed in front. Ties are broken by first-in-first-out.
  77. /// If the queue is full, the result is undefined.
  78. /// If the node is already enqueued, the result is undefined.
  79. /// O(log n)
  80. /// </summary>
  81. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  82. public void Enqueue(TItem node, TPriority priority)
  83. {
  84. #if DEBUG
  85. if (node == null)
  86. {
  87. throw new ArgumentNullException(nameof(node));
  88. }
  89. if (_numNodes >= _nodes.Length - 1)
  90. {
  91. throw new InvalidOperationException("Queue is full - node cannot be added: " + node);
  92. }
  93. if (Contains(node))
  94. {
  95. throw new InvalidOperationException("Node is already enqueued: " + node);
  96. }
  97. #endif
  98. node.Priority = priority;
  99. _numNodes++;
  100. _nodes[_numNodes] = node;
  101. node.QueueIndex = _numNodes;
  102. node.InsertionIndex = _numNodesEverEnqueued++;
  103. CascadeUp(_nodes[_numNodes]);
  104. }
  105. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  106. private void Swap(TItem node1, TItem node2)
  107. {
  108. //Swap the nodes
  109. _nodes[node1.QueueIndex] = node2;
  110. _nodes[node2.QueueIndex] = node1;
  111. //Swap their indicies
  112. int temp = node1.QueueIndex;
  113. node1.QueueIndex = node2.QueueIndex;
  114. node2.QueueIndex = temp;
  115. }
  116. //Performance appears to be slightly better when this is NOT inlined o_O
  117. private void CascadeUp(TItem node)
  118. {
  119. //aka Heapify-up
  120. int parent = node.QueueIndex / 2;
  121. while (parent >= 1)
  122. {
  123. var parentNode = _nodes[parent];
  124. if (HasHigherPriority(parentNode, node))
  125. break;
  126. //Node has lower priority value, so move it up the heap
  127. Swap(node, parentNode); //For some reason, this is faster with Swap() rather than (less..?) individual operations, like in CascadeDown()
  128. parent = node.QueueIndex / 2;
  129. }
  130. }
  131. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  132. private void CascadeDown(TItem node)
  133. {
  134. //aka Heapify-down
  135. TItem newParent;
  136. int finalQueueIndex = node.QueueIndex;
  137. while (true)
  138. {
  139. newParent = node;
  140. int childLeftIndex = 2 * finalQueueIndex;
  141. //Check if the left-child is higher-priority than the current node
  142. if (childLeftIndex > _numNodes)
  143. {
  144. //This could be placed outside the loop, but then we'd have to check newParent != node twice
  145. node.QueueIndex = finalQueueIndex;
  146. _nodes[finalQueueIndex] = node;
  147. break;
  148. }
  149. var childLeft = _nodes[childLeftIndex];
  150. if (HasHigherPriority(childLeft, newParent))
  151. {
  152. newParent = childLeft;
  153. }
  154. //Check if the right-child is higher-priority than either the current node or the left child
  155. int childRightIndex = childLeftIndex + 1;
  156. if (childRightIndex <= _numNodes)
  157. {
  158. var childRight = _nodes[childRightIndex];
  159. if (HasHigherPriority(childRight, newParent))
  160. {
  161. newParent = childRight;
  162. }
  163. }
  164. //If either of the children has higher (smaller) priority, swap and continue cascading
  165. if (newParent != node)
  166. {
  167. //Move new parent to its new index. node will be moved once, at the end
  168. //Doing it this way is one less assignment operation than calling Swap()
  169. _nodes[finalQueueIndex] = newParent;
  170. int temp = newParent.QueueIndex;
  171. newParent.QueueIndex = finalQueueIndex;
  172. finalQueueIndex = temp;
  173. }
  174. else
  175. {
  176. //See note above
  177. node.QueueIndex = finalQueueIndex;
  178. _nodes[finalQueueIndex] = node;
  179. break;
  180. }
  181. }
  182. }
  183. /// <summary>
  184. /// Returns true if 'higher' has higher priority than 'lower', false otherwise.
  185. /// Note that calling HasHigherPriority(node, node) (ie. both arguments the same node) will return false
  186. /// </summary>
  187. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  188. private bool HasHigherPriority(TItem higher, TItem lower)
  189. {
  190. var cmp = higher.Priority.CompareTo(lower.Priority);
  191. return (cmp < 0 || (cmp == 0 && higher.InsertionIndex < lower.InsertionIndex));
  192. }
  193. /// <summary>
  194. /// Removes the head of the queue (node with minimum priority; ties are broken by order of insertion), and returns it.
  195. /// If queue is empty, result is undefined
  196. /// O(log n)
  197. /// </summary>
  198. public bool TryDequeue(out TItem item)
  199. {
  200. if (_numNodes <= 0)
  201. {
  202. item = default(TItem);
  203. return false;
  204. }
  205. #if DEBUG
  206. if (!IsValidQueue())
  207. {
  208. throw new InvalidOperationException("Queue has been corrupted (Did you update a node priority manually instead of calling UpdatePriority()?" +
  209. "Or add the same node to two different queues?)");
  210. }
  211. #endif
  212. var returnMe = _nodes[1];
  213. Remove(returnMe);
  214. item = returnMe;
  215. return true;
  216. }
  217. /// <summary>
  218. /// Resize the queue so it can accept more nodes. All currently enqueued nodes are remain.
  219. /// Attempting to decrease the queue size to a size too small to hold the existing nodes results in undefined behavior
  220. /// O(n)
  221. /// </summary>
  222. public void Resize(int maxNodes)
  223. {
  224. #if DEBUG
  225. if (maxNodes <= 0)
  226. {
  227. throw new InvalidOperationException("Queue size cannot be smaller than 1");
  228. }
  229. if (maxNodes < _numNodes)
  230. {
  231. throw new InvalidOperationException("Called Resize(" + maxNodes + "), but current queue contains " + _numNodes + " nodes");
  232. }
  233. #endif
  234. TItem[] newArray = new TItem[maxNodes + 1];
  235. int highestIndexToCopy = Math.Min(maxNodes, _numNodes);
  236. for (int i = 1; i <= highestIndexToCopy; i++)
  237. {
  238. newArray[i] = _nodes[i];
  239. }
  240. _nodes = newArray;
  241. }
  242. /// <summary>
  243. /// Returns the head of the queue, without removing it (use Dequeue() for that).
  244. /// If the queue is empty, behavior is undefined.
  245. /// O(1)
  246. /// </summary>
  247. public TItem First
  248. {
  249. get
  250. {
  251. #if DEBUG
  252. if (_numNodes <= 0)
  253. {
  254. throw new InvalidOperationException("Cannot call .First on an empty queue");
  255. }
  256. #endif
  257. return _nodes[1];
  258. }
  259. }
  260. /// <summary>
  261. /// This method must be called on a node every time its priority changes while it is in the queue.
  262. /// <b>Forgetting to call this method will result in a corrupted queue!</b>
  263. /// Calling this method on a node not in the queue results in undefined behavior
  264. /// O(log n)
  265. /// </summary>
  266. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  267. public void UpdatePriority(TItem node, TPriority priority)
  268. {
  269. #if DEBUG
  270. if (node == null)
  271. {
  272. throw new ArgumentNullException(nameof(node));
  273. }
  274. if (!Contains(node))
  275. {
  276. throw new InvalidOperationException("Cannot call UpdatePriority() on a node which is not enqueued: " + node);
  277. }
  278. #endif
  279. node.Priority = priority;
  280. OnNodeUpdated(node);
  281. }
  282. private void OnNodeUpdated(TItem node)
  283. {
  284. //Bubble the updated node up or down as appropriate
  285. int parentIndex = node.QueueIndex / 2;
  286. var parentNode = _nodes[parentIndex];
  287. if (parentIndex > 0 && HasHigherPriority(node, parentNode))
  288. {
  289. CascadeUp(node);
  290. }
  291. else
  292. {
  293. //Note that CascadeDown will be called if parentNode == node (that is, node is the root)
  294. CascadeDown(node);
  295. }
  296. }
  297. /// <summary>
  298. /// Removes a node from the queue. The node does not need to be the head of the queue.
  299. /// If the node is not in the queue, the result is undefined. If unsure, check Contains() first
  300. /// O(log n)
  301. /// </summary>
  302. public void Remove(TItem node)
  303. {
  304. #if DEBUG
  305. if (node == null)
  306. {
  307. throw new ArgumentNullException(nameof(node));
  308. }
  309. if (!Contains(node))
  310. {
  311. throw new InvalidOperationException("Cannot call Remove() on a node which is not enqueued: " + node);
  312. }
  313. #endif
  314. //If the node is already the last node, we can remove it immediately
  315. if (node.QueueIndex == _numNodes)
  316. {
  317. _nodes[_numNodes] = null;
  318. _numNodes--;
  319. return;
  320. }
  321. //Swap the node with the last node
  322. var formerLastNode = _nodes[_numNodes];
  323. Swap(node, formerLastNode);
  324. _nodes[_numNodes] = null;
  325. _numNodes--;
  326. //Now bubble formerLastNode (which is no longer the last node) up or down as appropriate
  327. OnNodeUpdated(formerLastNode);
  328. }
  329. public IEnumerator<TItem> GetEnumerator()
  330. {
  331. for (int i = 1; i <= _numNodes; i++)
  332. yield return _nodes[i];
  333. }
  334. IEnumerator IEnumerable.GetEnumerator()
  335. {
  336. return GetEnumerator();
  337. }
  338. /// <summary>
  339. /// <b>Should not be called in production code.</b>
  340. /// Checks to make sure the queue is still in a valid state. Used for testing/debugging the queue.
  341. /// </summary>
  342. public bool IsValidQueue()
  343. {
  344. for (int i = 1; i < _nodes.Length; i++)
  345. {
  346. if (_nodes[i] != null)
  347. {
  348. int childLeftIndex = 2 * i;
  349. if (childLeftIndex < _nodes.Length && _nodes[childLeftIndex] != null && HasHigherPriority(_nodes[childLeftIndex], _nodes[i]))
  350. return false;
  351. int childRightIndex = childLeftIndex + 1;
  352. if (childRightIndex < _nodes.Length && _nodes[childRightIndex] != null && HasHigherPriority(_nodes[childRightIndex], _nodes[i]))
  353. return false;
  354. }
  355. }
  356. return true;
  357. }
  358. }
  359. }