| | 1 | | using System.Collections; |
| | 2 | |
|
| | 3 | | namespace MoreStructures.PriorityQueues.ArrayList; |
| | 4 | |
|
| | 5 | | /// <summary> |
| | 6 | | /// An <see cref="IPriorityQueue{T}"/> implementation based on an unsorted list of its items. On top of basic |
| | 7 | | /// operations it also supports <see cref="IUpdatablePriorityQueue{T}"/>, <see cref="IPeekKthPriorityQueue{T}"/> and |
| | 8 | | /// <see cref="IMergeablePriorityQueue{T, TPQTarget}"/>. |
| | 9 | | /// operations. |
| | 10 | | /// </summary> |
| | 11 | | /// <typeparam name="T"><inheritdoc cref="IPriorityQueue{T}"/></typeparam> |
| | 12 | | /// <remarks> |
| | 13 | | /// <para id="advantages"> |
| | 14 | | /// ADVANTAGES AND DISADVANTAGES |
| | 15 | | /// <br/> |
| | 16 | | /// This represents one of the simplest implementations of a Priority Queue. |
| | 17 | | /// <br/> |
| | 18 | | /// It provides O(1) count and amortized insertion, at the cost of all other operations, which are O(n). |
| | 19 | | /// <br/> |
| | 20 | | /// If insertion performance is the only highly critical operation, to the point that a constant time performance |
| | 21 | | /// is the only acceptable runtime, and not even the logarithmic time insertion of a tree-based solution can be |
| | 22 | | /// applied, this implementation may be the best choice, although lazy approaches such as |
| | 23 | | /// <see cref="FibonacciHeap.FibonacciHeapPriorityQueue{T}"/> can provide constant-time insertion performance, |
| | 24 | | /// while keeping sub-linear complexity for all other operations. |
| | 25 | | /// <br/> |
| | 26 | | /// If merging performance is also important, a solution based on linked lists can offer constant-time merging and |
| | 27 | | /// still similar simplicity of implementation, same insertion performance and same tradeoff in terms of the |
| | 28 | | /// complexity of all other operations. |
| | 29 | | /// <br/> |
| | 30 | | /// When data extraction performance is also a concern, or the main concern, a more balanced solution in terms of |
| | 31 | | /// complexity of its operations should be preferred. |
| | 32 | | /// <br/> |
| | 33 | | /// This implementation can also be useful as a benchmark baseline in tests, when comparing against more complex |
| | 34 | | /// solutions. |
| | 35 | | /// </para> |
| | 36 | | /// </remarks> |
| | 37 | | public sealed class ArrayListPriorityQueue<T> |
| | 38 | | : IUpdatablePriorityQueue<T>, IPeekKthPriorityQueue<T>, IMergeablePriorityQueue<T, ArrayListPriorityQueue<T>> |
| | 39 | | where T : notnull |
| | 40 | | { |
| | 41 | | /// <summary> |
| | 42 | | /// A non-negative, zero-based, monotonically strictly increasing counter, incremented at every insertion into this |
| | 43 | | /// data structure by a <see cref="Push(T, int)"/>. |
| | 44 | | /// </summary> |
| 13339 | 45 | | private int CurrentPushTimestamp { get; set; } = 0; |
| | 46 | |
|
| | 47 | | /// <summary> |
| | 48 | | /// The <see cref="List{T}"/> of <see cref="PrioritizedItem{T}"/> backing the array list heap. |
| | 49 | | /// </summary> |
| 1530825 | 50 | | private List<PrioritizedItem<T>> Items { get; } |
| | 51 | |
|
| | 52 | | private KeyValuePair<int, PrioritizedItem<T>> FindHighestPriorityOccurrence(T item) |
| 1156 | 53 | | { |
| 1156 | 54 | | return MoreLinq.MoreEnumerable |
| 1156 | 55 | | .Index(Items) |
| 5015 | 56 | | .Where(kvp => Equals(kvp.Value.Item, item)) |
| 1156 | 57 | | .DefaultIfEmpty(KeyValuePair.Create(-1, new PrioritizedItem<T>())) |
| 2435 | 58 | | .MaxBy(kvp => kvp.Value); |
| 1156 | 59 | | } |
| | 60 | |
|
| | 61 | | /// <summary> |
| | 62 | | /// Builds a priority queue using the provided list as <b>direct</b> backing structure. |
| | 63 | | /// </summary> |
| | 64 | | /// <param name="items">The <see cref="List{T}"/> structure to be used as backing structure.</param> |
| | 65 | | /// <remarks> |
| | 66 | | /// The provided list is not copied over: it is used directly as backing structure for the queue. |
| | 67 | | /// <br/> |
| | 68 | | /// Therefore, operations mutating the queue such as <see cref="Push(T, int)"/> will alter the content of the |
| | 69 | | /// <paramref name="items"/> list. |
| | 70 | | /// </remarks> |
| 507 | 71 | | public ArrayListPriorityQueue(List<PrioritizedItem<T>> items) |
| 507 | 72 | | { |
| 507 | 73 | | Items = items; |
| 507 | 74 | | } |
| | 75 | |
|
| | 76 | | /// <summary> |
| | 77 | | /// Builds an empty priority queue. |
| | 78 | | /// </summary> |
| 505 | 79 | | public ArrayListPriorityQueue() : this(new List<PrioritizedItem<T>>()) |
| 505 | 80 | | { |
| 505 | 81 | | } |
| | 82 | |
|
| | 83 | | /// <summary> |
| | 84 | | /// Builds a priority queue using the provided items to populate its backing structure. |
| | 85 | | /// </summary> |
| | 86 | | /// <param name="items">The items to be added to the queue.</param> |
| | 87 | | /// <remarks> |
| | 88 | | /// The provided sequence is enumerated and copied over onto a dedicated list: it is not used directly as backing |
| | 89 | | /// structure for the queue. |
| | 90 | | /// <br/> |
| | 91 | | /// Therefore, operations mutating the queue won't alter the provided <paramref name="items"/> sequence. |
| | 92 | | /// </remarks> |
| 1 | 93 | | public ArrayListPriorityQueue(IEnumerable<PrioritizedItem<T>> items) : this(items.ToList()) |
| 1 | 94 | | { |
| 1 | 95 | | } |
| | 96 | |
|
| | 97 | | /// <inheritdoc path="//*[not(self::remarks)]"/> |
| | 98 | | /// <remarks> |
| | 99 | | /// Calls <see cref="Count"/> on the underlying list. |
| | 100 | | /// <br/> |
| | 101 | | /// Time and Space Complexity are O(1). |
| | 102 | | /// </remarks> |
| 1198 | 103 | | public int Count => Items.Count; |
| | 104 | |
|
| | 105 | | /// <inheritdoc path="//*[not(self::remarks)]"/> |
| | 106 | | /// <remarks> |
| | 107 | | /// Sorts the underlying list in descending order of priority and selects the items. |
| | 108 | | /// <br/> |
| | 109 | | /// Time Complexity is O(n * log(n)) (when fully enumerated). Space Complexity is O(n), as required by sorting. |
| | 110 | | /// </remarks> |
| 152 | 111 | | public IEnumerator<T> GetEnumerator() => Items |
| 2893 | 112 | | .OrderByDescending(itemAndPriority => itemAndPriority.Priority) |
| 2889 | 113 | | .Select(itemAndPriority => itemAndPriority.Item) |
| 152 | 114 | | .GetEnumerator(); |
| | 115 | |
|
| | 116 | | /// <inheritdoc path="//*[not(self::remarks)]"/> |
| | 117 | | /// <remarks> |
| | 118 | | /// <inheritdoc cref="GetEnumerator"/> |
| | 119 | | /// </remarks> |
| 1 | 120 | | IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); |
| | 121 | |
|
| | 122 | | /// <inheritdoc path="//*[not(self::remarks)]"/> |
| | 123 | | /// <remarks> |
| | 124 | | /// Linearly scans the underlying list looking for the highest priority. |
| | 125 | | /// <br/> |
| | 126 | | /// Time Complexity is O(n). Space Complexity is O(1). |
| | 127 | | /// </remarks> |
| 269 | 128 | | public PrioritizedItem<T> Peek() => Items.MaxBy(itemAndPriority => itemAndPriority.Priority); |
| | 129 | |
|
| | 130 | | /// <inheritdoc path="//*[not(self::remarks)]"/> |
| | 131 | | /// <remarks> |
| | 132 | | /// Linearly scans the underlying list looking for the index with the highest priority. |
| | 133 | | /// <br/> |
| | 134 | | /// Then removes the item with such index from the underlying list and returns it as result. |
| | 135 | | /// <br/> |
| | 136 | | /// Time Complexity is O(n). Space Complexity is O(1). |
| | 137 | | /// </remarks> |
| | 138 | | public PrioritizedItem<T> Pop() |
| 2070 | 139 | | { |
| 2070 | 140 | | if (Items.Count == 0) |
| 3 | 141 | | throw new InvalidOperationException($"Can't ${nameof(Pop)} on an empty queue."); |
| | 142 | |
|
| 2067 | 143 | | var maxIndex = 0; |
| 1012724 | 144 | | for (var i = 1; i < Items.Count; i++) |
| 504295 | 145 | | if (Items[maxIndex].Priority < Items[i].Priority) |
| 2151 | 146 | | maxIndex = i; |
| | 147 | |
|
| 2067 | 148 | | var result = Items[maxIndex]; |
| 2067 | 149 | | Items.RemoveAt(maxIndex); |
| 2067 | 150 | | return result; |
| 2067 | 151 | | } |
| | 152 | |
|
| | 153 | | /// <inheritdoc path="//*[not(self::remarks)]"/> |
| | 154 | | /// <remarks> |
| | 155 | | /// Appends the provided <paramref name="item"/> with its <paramref name="priority"/> to the end of the underlying |
| | 156 | | /// list. |
| | 157 | | /// <br/> |
| | 158 | | /// Time Complexity is O(n). Space Complexity is O(1) (amortized over multiple executions of |
| | 159 | | /// <see cref="Push(T, int)"/>). |
| | 160 | | /// </remarks> |
| | 161 | | public void Push(T item, int priority) |
| 6416 | 162 | | { |
| 6416 | 163 | | Items.Add(new(item, priority, CurrentPushTimestamp++)); |
| 6416 | 164 | | } |
| | 165 | |
|
| | 166 | | /// <inheritdoc path="//*[not(self::remarks)]"/> |
| | 167 | | /// <remarks> |
| | 168 | | /// Linearly scans the underlying list looking for <see cref="PrioritizedItem{T}"/> having an item equals to the |
| | 169 | | /// provided <paramref name="item"/> (<see cref="object.Equals(object?, object?)"/> is used to compare the two |
| | 170 | | /// items of type <typeparamref name="T"/>). |
| | 171 | | /// <br/> |
| | 172 | | /// It then selects all priorities found for <paramref name="item"/> and builds a |
| | 173 | | /// <see cref="ArrayListPriorityQueue{T}"/> of <see cref="int"/> values out of them. |
| | 174 | | /// <br/> |
| | 175 | | /// Such a priority queue is returned as result. |
| | 176 | | /// <br/> |
| | 177 | | /// Time Complexity is O(n * Teq) and Space Complexity is O(Seq), where Teq and Seq are the time and space cost of |
| | 178 | | /// comparing two items of type <typeparamref name="T"/>. |
| | 179 | | /// </remarks> |
| | 180 | | public IEnumerable<int> GetPrioritiesOf(T item) |
| 41 | 181 | | { |
| 41 | 182 | | var priorities = Items |
| 78 | 183 | | .Where(prioritizedItem => Equals(prioritizedItem.Item, item)) |
| 85 | 184 | | .Select(prioritizedItem => prioritizedItem.Priority); |
| 41 | 185 | | var priorityQueue = new ArrayListPriorityQueue<int>(); |
| 211 | 186 | | foreach (var priority in priorities) |
| 44 | 187 | | priorityQueue.Push(priority, priority); |
| 41 | 188 | | return priorityQueue; |
| 41 | 189 | | } |
| | 190 | |
|
| | 191 | | /// <inheritdoc path="//*[not(self::remarks)]"/> |
| | 192 | | /// <remarks> |
| | 193 | | /// Linearly scans the underlying list looking for the index of the item equals to the provided |
| | 194 | | /// <paramref name="item"/> (<see cref="object.Equals(object?, object?)"/> is used to compare the two items of type |
| | 195 | | /// <typeparamref name="T"/>) <b>with the highest priority</b>. |
| | 196 | | /// <br/> |
| | 197 | | /// If multiple occurrences of <paramref name="item"/> are present with the same highest priority, the one with the |
| | 198 | | /// lowest <see cref="PrioritizedItem{T}.PushTimestamp"/> is selected, to guarantee <b>stability</b>. |
| | 199 | | /// <br/> |
| | 200 | | /// If no occurrence of <paramref name="item"/> is found, a <see cref="InvalidOperationException"/> is raised. |
| | 201 | | /// <br/> |
| | 202 | | /// Then replaces the <see cref="PrioritizedItem{T}"/> at such index with a new one having same |
| | 203 | | /// <see cref="PrioritizedItem{T}.Item"/> and <see cref="PrioritizedItem{T}.PushTimestamp"/>, but |
| | 204 | | /// <see cref="PrioritizedItem{T}.Priority"/> set to <paramref name="newPriority"/>. |
| | 205 | | /// <br/> |
| | 206 | | /// Finally returns the previously stored <see cref="PrioritizedItem{T}"/> at that index. |
| | 207 | | /// <br/> |
| | 208 | | /// Time Complexity is O(n * Teq) and Space Complexity is O(Seq), where Teq and Seq are the time and space cost of |
| | 209 | | /// comparing two items of type <typeparamref name="T"/>. |
| | 210 | | /// </remarks> |
| | 211 | | public PrioritizedItem<T> UpdatePriority(T item, int newPriority) |
| 97 | 212 | | { |
| 97 | 213 | | var oldItem = Remove(item); |
| 97 | 214 | | if (oldItem == null) |
| 3 | 215 | | throw new InvalidOperationException("The specified item is not in the queue."); |
| 94 | 216 | | Push(item, newPriority); |
| 94 | 217 | | return oldItem.Value; |
| 94 | 218 | | } |
| | 219 | |
|
| | 220 | | /// <inheritdoc path="//*[not(self::remarks)]"/> |
| | 221 | | /// <remarks> |
| | 222 | | /// Linearly scans the underlying list looking for the index of the item equals to the provided |
| | 223 | | /// <paramref name="item"/> (<see cref="object.Equals(object?, object?)"/> is used to compare the two items of type |
| | 224 | | /// <typeparamref name="T"/>). |
| | 225 | | /// <br/> |
| | 226 | | /// If multiple occurrences of <paramref name="item"/> are present with the same highest priority, the one with the |
| | 227 | | /// lowest <see cref="PrioritizedItem{T}.PushTimestamp"/> is selected, to guarantee <b>stability</b>. |
| | 228 | | /// <br/> |
| | 229 | | /// If no such index is found, nothing is changed and <see langword="null"/> is returned. |
| | 230 | | /// <br/> |
| | 231 | | /// Otherwise the item at such position is removed from the list and returned as result. |
| | 232 | | /// <br/> |
| | 233 | | /// Time Complexity is O(n * Teq) and Space Complexity is O(Seq), where Teq and Seq are the time and space cost of |
| | 234 | | /// comparing two items of type <typeparamref name="T"/>. |
| | 235 | | /// </remarks> |
| | 236 | | public PrioritizedItem<T>? Remove(T item) |
| 1156 | 237 | | { |
| 1156 | 238 | | var indexAndPrioritizedItem = FindHighestPriorityOccurrence(item); |
| | 239 | |
|
| 1156 | 240 | | if (indexAndPrioritizedItem.Key < 0) |
| 868 | 241 | | return null; |
| | 242 | |
|
| 288 | 243 | | Items.RemoveAt(indexAndPrioritizedItem.Key); |
| 288 | 244 | | return indexAndPrioritizedItem.Value; |
| 1156 | 245 | | } |
| | 246 | |
|
| | 247 | | /// <inheritdoc path="//*[not(self::remarks)]"/> |
| | 248 | | /// <remarks> |
| | 249 | | /// Uses the Quick Select algorithm to find the <paramref name="k"/>-th largest element by |
| | 250 | | /// <see cref="PrioritizedItem{T}.Priority"/> in the underlying list. |
| | 251 | | /// <br/> |
| | 252 | | /// Because Quick Select requires at least partial in-place sorting, the entire content of the underlying list is |
| | 253 | | /// first copied into a temporary list, which is passed as target to the Quick Select procedure. |
| | 254 | | /// <br/> |
| | 255 | | /// Selected pivot is always at the end of the range of indexes in which selection is happening. |
| | 256 | | /// <br/> |
| | 257 | | /// So If input is already sorted in ascending order, Time Complexity is O(n^2), whereas in the average case Time |
| | 258 | | /// Complexity is O(n). Space Complexity is always O(n). |
| | 259 | | /// </remarks> |
| | 260 | | public PrioritizedItem<T>? PeekKth(int k) |
| 36 | 261 | | { |
| 36 | 262 | | if (k < 0) |
| 2 | 263 | | throw new ArgumentException("Must be non-negative.", nameof(k)); |
| 34 | 264 | | if (k >= Items.Count) |
| 8 | 265 | | return null; |
| 26 | 266 | | if (k == 0) |
| 6 | 267 | | return Peek(); |
| | 268 | |
|
| 20 | 269 | | var list = Items.ToList(); |
| 20 | 270 | | var index = QuickFind(list, k, 0, list.Count - 1); |
| 20 | 271 | | return list[index]; |
| 34 | 272 | | } |
| | 273 | |
|
| | 274 | | private static int QuickFind(List<PrioritizedItem<T>> list, int k, int start, int end) |
| 73 | 275 | | { |
| 75 | 276 | | if (start == end) return start; |
| | 277 | |
|
| 71 | 278 | | int currentPivotIndex = Partition(list, start, end); |
| | 279 | |
|
| 89 | 280 | | if (currentPivotIndex == k) return currentPivotIndex; |
| 101 | 281 | | if (currentPivotIndex > k) return QuickFind(list, k, start, currentPivotIndex - 1); |
| 5 | 282 | | return QuickFind(list, k, currentPivotIndex + 1, end); |
| 73 | 283 | | } |
| | 284 | |
|
| | 285 | | private static int Partition(List<PrioritizedItem<T>> list, int start, int end) |
| 71 | 286 | | { |
| 71 | 287 | | var pivotValue = list[end]; |
| 71 | 288 | | int currentPivotIndex = start - 1; |
| 882 | 289 | | for (var j = start; j < end; j++) // Start included, end excluded |
| 370 | 290 | | { |
| 370 | 291 | | if (list[j].CompareTo(pivotValue) >= 0) |
| 348 | 292 | | { |
| 348 | 293 | | currentPivotIndex++; |
| 348 | 294 | | (list[currentPivotIndex], list[j]) = (list[j], list[currentPivotIndex]); |
| 348 | 295 | | } |
| 370 | 296 | | } |
| | 297 | |
|
| 71 | 298 | | currentPivotIndex++; |
| 71 | 299 | | (list[currentPivotIndex], list[end]) = (list[end], list[currentPivotIndex]); |
| 71 | 300 | | return currentPivotIndex; |
| 71 | 301 | | } |
| | 302 | |
|
| | 303 | | /// <inheritdoc path="//*[not(self::remarks)]"/> |
| | 304 | | /// <remarks> |
| | 305 | | /// Just pushes all items in the <paramref name="targetPriorityQueue"/> via <see cref="Push(T, int)"/>, which |
| | 306 | | /// appends each item to the end. |
| | 307 | | /// <br/> |
| | 308 | | /// Then clears the content of the <paramref name="targetPriorityQueue"/>, to respect the contract defined by |
| | 309 | | /// <see cref="IMergeablePriorityQueue{T, TPQTarget}"/>. |
| | 310 | | /// <br/> |
| | 311 | | /// Because the underlying structures of both source and target is an array list, there isn't an effective strategy |
| | 312 | | /// for achieving sub-linear performance, and <see cref="Push(T, int)"/> gives the optimal linear performance. |
| | 313 | | /// <br/> |
| | 314 | | /// Time and Space Complexity are O(m), where m is the number of items in the target. |
| | 315 | | /// </remarks> |
| | 316 | | public void MergeFrom(ArrayListPriorityQueue<T> targetPriorityQueue) |
| 119 | 317 | | { |
| 2991 | 318 | | foreach (var prioritizedItem in targetPriorityQueue.Items) |
| 1317 | 319 | | Push(prioritizedItem.Item, prioritizedItem.Priority); |
| 119 | 320 | | targetPriorityQueue.Clear(); |
| 119 | 321 | | } |
| | 322 | |
|
| | 323 | | /// <inheritdoc path="//*[not(self::remarks)]"/> |
| | 324 | | /// <remarks> |
| | 325 | | /// Just clears the underlying array list. |
| | 326 | | /// <br/> |
| | 327 | | /// Time and Space Complexity is O(1). |
| | 328 | | /// </remarks> |
| | 329 | | public void Clear() |
| 174 | 330 | | { |
| 174 | 331 | | Items.Clear(); |
| 174 | 332 | | } |
| | 333 | | } |