MB3_PriorityQueue.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. using UnityEngine;
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. namespace DigitalOpus.MB.Core
  6. {
  7. /// From https://www.codeproject.com/Articles/126751/Priority-queue-in-Csharp-with-help-of-heap-data-st.aspx
  8. /// <summary>
  9. /// Priority queue based on binary heap,
  10. /// Elements with minimum priority dequeued first
  11. /// </summary>
  12. /// <typeparam name="TPriority">Type of priorities</typeparam>
  13. /// <typeparam name="TValue">Type of values</typeparam>
  14. public class PriorityQueue<TPriority, TValue> : ICollection<KeyValuePair<TPriority, TValue>>
  15. {
  16. public List<KeyValuePair<TPriority, TValue>> _baseHeap;
  17. private IComparer<TPriority> _comparer;
  18. #region Constructors
  19. /// <summary>
  20. /// Initializes a new instance of priority queue with default initial capacity and default priority comparer
  21. /// </summary>
  22. public PriorityQueue()
  23. : this(Comparer<TPriority>.Default)
  24. {
  25. }
  26. /// <summary>
  27. /// Initializes a new instance of priority queue with specified initial capacity and default priority comparer
  28. /// </summary>
  29. /// <param name="capacity">initial capacity</param>
  30. public PriorityQueue(int capacity)
  31. : this(capacity, Comparer<TPriority>.Default)
  32. {
  33. }
  34. /// <summary>
  35. /// Initializes a new instance of priority queue with specified initial capacity and specified priority comparer
  36. /// </summary>
  37. /// <param name="capacity">initial capacity</param>
  38. /// <param name="comparer">priority comparer</param>
  39. public PriorityQueue(int capacity, IComparer<TPriority> comparer)
  40. {
  41. if (comparer == null)
  42. throw new ArgumentNullException();
  43. _baseHeap = new List<KeyValuePair<TPriority, TValue>>(capacity);
  44. _comparer = comparer;
  45. }
  46. /// <summary>
  47. /// Initializes a new instance of priority queue with default initial capacity and specified priority comparer
  48. /// </summary>
  49. /// <param name="comparer">priority comparer</param>
  50. public PriorityQueue(IComparer<TPriority> comparer)
  51. {
  52. if (comparer == null)
  53. throw new ArgumentNullException();
  54. _baseHeap = new List<KeyValuePair<TPriority, TValue>>();
  55. _comparer = comparer;
  56. }
  57. /// <summary>
  58. /// Initializes a new instance of priority queue with specified data and default priority comparer
  59. /// </summary>
  60. /// <param name="data">data to be inserted into priority queue</param>
  61. public PriorityQueue(IEnumerable<KeyValuePair<TPriority, TValue>> data)
  62. : this(data, Comparer<TPriority>.Default)
  63. {
  64. }
  65. /// <summary>
  66. /// Initializes a new instance of priority queue with specified data and specified priority comparer
  67. /// </summary>
  68. /// <param name="data">data to be inserted into priority queue</param>
  69. /// <param name="comparer">priority comparer</param>
  70. public PriorityQueue(IEnumerable<KeyValuePair<TPriority, TValue>> data, IComparer<TPriority> comparer)
  71. {
  72. if (data == null || comparer == null)
  73. throw new ArgumentNullException();
  74. _comparer = comparer;
  75. _baseHeap = new List<KeyValuePair<TPriority, TValue>>(data);
  76. // heapify data
  77. for (int pos = _baseHeap.Count / 2 - 1; pos >= 0; pos--)
  78. HeapifyFromBeginningToEnd(pos);
  79. }
  80. #endregion
  81. #region Merging
  82. /// <summary>
  83. /// Merges two priority queues
  84. /// </summary>
  85. /// <param name="pq1">first priority queue</param>
  86. /// <param name="pq2">second priority queue</param>
  87. /// <returns>resultant priority queue</returns>
  88. /// <remarks>
  89. /// source priority queues must have equal comparers,
  90. /// otherwise <see cref="InvalidOperationException"/> will be thrown
  91. /// </remarks>
  92. public static PriorityQueue<TPriority, TValue> MergeQueues(PriorityQueue<TPriority, TValue> pq1, PriorityQueue<TPriority, TValue> pq2)
  93. {
  94. if (pq1 == null || pq2 == null)
  95. throw new ArgumentNullException();
  96. if (pq1._comparer != pq2._comparer)
  97. throw new InvalidOperationException("Priority queues to be merged must have equal comparers");
  98. return MergeQueues(pq1, pq2, pq1._comparer);
  99. }
  100. /// <summary>
  101. /// Merges two priority queues and sets specified comparer for resultant priority queue
  102. /// </summary>
  103. /// <param name="pq1">first priority queue</param>
  104. /// <param name="pq2">second priority queue</param>
  105. /// <param name="comparer">comparer for resultant priority queue</param>
  106. /// <returns>resultant priority queue</returns>
  107. public static PriorityQueue<TPriority, TValue> MergeQueues(PriorityQueue<TPriority, TValue> pq1, PriorityQueue<TPriority, TValue> pq2, IComparer<TPriority> comparer)
  108. {
  109. if (pq1 == null || pq2 == null || comparer == null)
  110. throw new ArgumentNullException();
  111. // merge data
  112. PriorityQueue<TPriority, TValue> result = new PriorityQueue<TPriority, TValue>(pq1.Count + pq2.Count, pq1._comparer);
  113. result._baseHeap.AddRange(pq1._baseHeap);
  114. result._baseHeap.AddRange(pq2._baseHeap);
  115. // heapify data
  116. for (int pos = result._baseHeap.Count / 2 - 1; pos >= 0; pos--)
  117. result.HeapifyFromBeginningToEnd(pos);
  118. return result;
  119. }
  120. #endregion
  121. #region Priority queue operations
  122. /// <summary>
  123. /// Enqueues element into priority queue
  124. /// </summary>
  125. /// <param name="priority">element priority</param>
  126. /// <param name="value">element value</param>
  127. public void Enqueue(TPriority priority, TValue value)
  128. {
  129. Insert(priority, value);
  130. }
  131. /// <summary>
  132. /// Dequeues element with minimum priority and return its priority and value as <see cref="KeyValuePair{TPriority,TValue}"/>
  133. /// </summary>
  134. /// <returns>priority and value of the dequeued element</returns>
  135. /// <remarks>
  136. /// Method throws <see cref="InvalidOperationException"/> if priority queue is empty
  137. /// </remarks>
  138. public KeyValuePair<TPriority, TValue> Dequeue()
  139. {
  140. if (!IsEmpty)
  141. {
  142. KeyValuePair<TPriority, TValue> result = _baseHeap[0];
  143. DeleteRoot();
  144. return result;
  145. }
  146. else
  147. throw new InvalidOperationException("Priority queue is empty");
  148. }
  149. /// <summary>
  150. /// Dequeues element with minimum priority and return its value
  151. /// </summary>
  152. /// <returns>value of the dequeued element</returns>
  153. /// <remarks>
  154. /// Method throws <see cref="InvalidOperationException"/> if priority queue is empty
  155. /// </remarks>
  156. public TValue DequeueValue()
  157. {
  158. return Dequeue().Value;
  159. }
  160. /// <summary>
  161. /// Returns priority and value of the element with minimun priority, without removing it from the queue
  162. /// </summary>
  163. /// <returns>priority and value of the element with minimum priority</returns>
  164. /// <remarks>
  165. /// Method throws <see cref="InvalidOperationException"/> if priority queue is empty
  166. /// </remarks>
  167. public KeyValuePair<TPriority, TValue> Peek()
  168. {
  169. if (!IsEmpty)
  170. return _baseHeap[0];
  171. else
  172. throw new InvalidOperationException("Priority queue is empty");
  173. }
  174. /// <summary>
  175. /// Returns value of the element with minimun priority, without removing it from the queue
  176. /// </summary>
  177. /// <returns>value of the element with minimum priority</returns>
  178. /// <remarks>
  179. /// Method throws <see cref="InvalidOperationException"/> if priority queue is empty
  180. /// </remarks>
  181. public TValue PeekValue()
  182. {
  183. return Peek().Value;
  184. }
  185. /// <summary>
  186. /// Gets whether priority queue is empty
  187. /// </summary>
  188. public bool IsEmpty
  189. {
  190. get { return _baseHeap.Count == 0; }
  191. }
  192. #endregion
  193. #region Heap operations
  194. private void ExchangeElements(int pos1, int pos2)
  195. {
  196. KeyValuePair<TPriority, TValue> val = _baseHeap[pos1];
  197. _baseHeap[pos1] = _baseHeap[pos2];
  198. _baseHeap[pos2] = val;
  199. }
  200. private void Insert(TPriority priority, TValue value)
  201. {
  202. KeyValuePair<TPriority, TValue> val = new KeyValuePair<TPriority, TValue>(priority, value);
  203. _baseHeap.Add(val);
  204. // heap[i] have children heap[2*i + 1] and heap[2*i + 2] and parent heap[(i-1)/ 2];
  205. // heapify after insert, from end to beginning
  206. HeapifyFromEndToBeginning(_baseHeap.Count - 1);
  207. }
  208. private int HeapifyFromEndToBeginning(int pos)
  209. {
  210. if (pos >= _baseHeap.Count) return -1;
  211. while (pos > 0)
  212. {
  213. int parentPos = (pos - 1) / 2;
  214. if (_comparer.Compare(_baseHeap[parentPos].Key, _baseHeap[pos].Key) > 0)
  215. {
  216. ExchangeElements(parentPos, pos);
  217. pos = parentPos;
  218. }
  219. else break;
  220. }
  221. return pos;
  222. }
  223. private void DeleteRoot()
  224. {
  225. if (_baseHeap.Count <= 1)
  226. {
  227. _baseHeap.Clear();
  228. return;
  229. }
  230. _baseHeap[0] = _baseHeap[_baseHeap.Count - 1];
  231. _baseHeap.RemoveAt(_baseHeap.Count - 1);
  232. // heapify
  233. HeapifyFromBeginningToEnd(0);
  234. }
  235. private void HeapifyFromBeginningToEnd(int pos)
  236. {
  237. if (pos >= _baseHeap.Count) return;
  238. // heap[i] have children heap[2*i + 1] and heap[2*i + 2] and parent heap[(i-1)/ 2];
  239. while (true)
  240. {
  241. // on each iteration exchange element with its smallest child
  242. int smallest = pos;
  243. int left = 2 * pos + 1;
  244. int right = 2 * pos + 2;
  245. if (left < _baseHeap.Count && _comparer.Compare(_baseHeap[smallest].Key, _baseHeap[left].Key) > 0)
  246. smallest = left;
  247. if (right < _baseHeap.Count && _comparer.Compare(_baseHeap[smallest].Key, _baseHeap[right].Key) > 0)
  248. smallest = right;
  249. if (smallest != pos)
  250. {
  251. ExchangeElements(smallest, pos);
  252. pos = smallest;
  253. }
  254. else break;
  255. }
  256. }
  257. #endregion
  258. #region ICollection<KeyValuePair<TPriority, TValue>> implementation
  259. /// <summary>
  260. /// Enqueus element into priority queue
  261. /// </summary>
  262. /// <param name="item">element to add</param>
  263. public void Add(KeyValuePair<TPriority, TValue> item)
  264. {
  265. Enqueue(item.Key, item.Value);
  266. }
  267. /// <summary>
  268. /// Clears the collection
  269. /// </summary>
  270. public void Clear()
  271. {
  272. _baseHeap.Clear();
  273. }
  274. /// <summary>
  275. /// Determines whether the priority queue contains a specific element
  276. /// </summary>
  277. /// <param name="item">The object to locate in the priority queue</param>
  278. /// <returns><c>true</c> if item is found in the priority queue; otherwise, <c>false.</c> </returns>
  279. public bool Contains(KeyValuePair<TPriority, TValue> item)
  280. {
  281. return _baseHeap.Contains(item);
  282. }
  283. public bool TryFindValue(TPriority item,out TValue foundVersion){
  284. for (int i = 0; i < _baseHeap.Count; i++) {
  285. if (_comparer.Compare(item,_baseHeap[i].Key) == 0){
  286. foundVersion = _baseHeap[i].Value;
  287. return true;
  288. }
  289. }
  290. foundVersion = default(TValue);
  291. return false;
  292. }
  293. /// <summary>
  294. /// Gets number of elements in the priority queue
  295. /// </summary>
  296. public int Count
  297. {
  298. get { return _baseHeap.Count; }
  299. }
  300. /// <summary>
  301. /// Copies the elements of the priority queue to an Array, starting at a particular Array index.
  302. /// </summary>
  303. /// <param name="array">The one-dimensional Array that is the destination of the elements copied from the priority queue. The Array must have zero-based indexing. </param>
  304. /// <param name="arrayIndex">The zero-based index in array at which copying begins.</param>
  305. /// <remarks>
  306. /// It is not guaranteed that items will be copied in the sorted order.
  307. /// </remarks>
  308. public void CopyTo(KeyValuePair<TPriority, TValue>[] array, int arrayIndex)
  309. {
  310. _baseHeap.CopyTo(array, arrayIndex);
  311. }
  312. /// <summary>
  313. /// Gets a value indicating whether the collection is read-only.
  314. /// </summary>
  315. /// <remarks>
  316. /// For priority queue this property returns <c>false</c>.
  317. /// </remarks>
  318. public bool IsReadOnly
  319. {
  320. get { return false; }
  321. }
  322. /// <summary>
  323. /// Removes the first occurrence of a specific object from the priority queue.
  324. /// </summary>
  325. /// <param name="item">The object to remove from the ICollection <(Of <(T >)>). </param>
  326. /// <returns><c>true</c> if item was successfully removed from the priority queue.
  327. /// This method returns false if item is not found in the collection. </returns>
  328. public bool Remove(KeyValuePair<TPriority, TValue> item)
  329. {
  330. // find element in the collection and remove it
  331. int elementIdx = _baseHeap.IndexOf(item);
  332. if (elementIdx < 0) return false;
  333. //remove element
  334. _baseHeap[elementIdx] = _baseHeap[_baseHeap.Count - 1];
  335. _baseHeap.RemoveAt(_baseHeap.Count - 1);
  336. // heapify
  337. int newPos = HeapifyFromEndToBeginning(elementIdx);
  338. if (newPos == elementIdx)
  339. HeapifyFromBeginningToEnd(elementIdx);
  340. return true;
  341. }
  342. /// <summary>
  343. /// Returns an enumerator that iterates through the collection.
  344. /// </summary>
  345. /// <returns>Enumerator</returns>
  346. /// <remarks>
  347. /// Returned enumerator does not iterate elements in sorted order.</remarks>
  348. public IEnumerator<KeyValuePair<TPriority, TValue>> GetEnumerator()
  349. {
  350. return _baseHeap.GetEnumerator();
  351. }
  352. /// <summary>
  353. /// Returns an enumerator that iterates through the collection.
  354. /// </summary>
  355. /// <returns>Enumerator</returns>
  356. /// <remarks>
  357. /// Returned enumerator does not iterate elements in sorted order.</remarks>
  358. IEnumerator IEnumerable.GetEnumerator()
  359. {
  360. return this.GetEnumerator();
  361. }
  362. #endregion
  363. }
  364. }