/* * Copyright 2022 Peter Han * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; namespace PeterHan.PLib.Core { /// /// A class similar to Queue that allows efficient access to its /// items in ascending order. /// public class PriorityQueue where T : IComparable { /// /// Returns the index of the specified item's first child. Its second child index is /// that index plus one. /// /// The item index. /// The index of its first child. private static int ChildIndex(int index) { return 2 * index + 1; } /// /// Returns the index of the specified item's parent. /// /// The item index. /// The index of its parent. private static int ParentIndex(int index) { return (index - 1) / 2; } /// /// The number of elements in this queue. /// public int Count => heap.Count; /// /// The heap where the items are stored. /// private readonly IList heap; /// /// Creates a new PriorityQueue<> with the default /// initial capacity. /// public PriorityQueue() : this(32) { } /// /// Creates a new PriorityQueue<> with the specified /// initial capacity. /// /// The initial capacity of this queue. public PriorityQueue(int capacity) { if (capacity < 1) throw new ArgumentException("capacity > 0"); heap = new List(Math.Max(capacity, 8)); } /// /// Removes all objects from this PriorityQueue<>. /// public void Clear() { heap.Clear(); } /// /// Returns whether the specified key is present in this priority queue. This operation /// is fairly slow, use with caution. /// /// The key to check. /// true if it exists in this priority queue, or false otherwise. public bool Contains(T key) { return heap.Contains(key); } /// /// Removes and returns the smallest object in the /// PriorityQueue<>. /// /// If multiple objects are the smallest object, an unspecified one is returned. /// /// The object that is removed from this PriorityQueue. /// If this queue is empty. public T Dequeue() { int index = 0, length = heap.Count, childIndex; if (length == 0) throw new InvalidOperationException("Queue is empty"); T top = heap[0]; // Put the last element as the new head heap[0] = heap[--length]; heap.RemoveAt(length); while ((childIndex = ChildIndex(index)) < length) { T first = heap[index], child = heap[childIndex]; if (childIndex < length - 1) { var rightChild = heap[childIndex + 1]; // Select the smallest child if (child.CompareTo(rightChild) > 0) { childIndex++; child = rightChild; } } if (first.CompareTo(child) < 0) break; heap[childIndex] = first; heap[index] = child; index = childIndex; } return top; } /// /// Adds an object to the PriorityQueue<>. /// /// The object to add to this PriorityQueue. /// If item is null. public void Enqueue(T item) { if (item == null) throw new ArgumentNullException(nameof(item)); int index = heap.Count; heap.Add(item); while (index > 0) { int parentIndex = ParentIndex(index); T first = heap[index], parent = heap[parentIndex]; if (first.CompareTo(parent) > 0) break; heap[parentIndex] = first; heap[index] = parent; index = parentIndex; } } /// /// Returns the smallest object in the PriorityQueue<> /// without removing it. /// /// If multiple objects are the smallest object, an unspecified one is returned. /// /// The smallest object in this PriorityQueue. /// If this queue is empty. public T Peek() { if (Count == 0) throw new InvalidOperationException("Queue is empty"); return heap[0]; } public override string ToString() { return heap.ToString(); } } /// /// A priority queue that includes a paired value. /// /// The type to use for the sorting in the PriorityQueue. /// The type to include as extra data. public sealed class PriorityDictionary : PriorityQueue. PriorityQueuePair> where K : IComparable { /// /// Creates a new PriorityDictionary<, /// > with the default initial capacity. /// public PriorityDictionary() : base() { } /// /// Creates a new PriorityDictionary<, /// > with the specified initial capacity. /// /// The initial capacity of this dictionary. public PriorityDictionary(int capacity) : base(capacity) { } /// /// Removes and returns the smallest object in the /// PriorityDictionary<, >. /// /// If multiple objects are the smallest object, an unspecified one is returned. /// /// The key of the object removed. /// The value of the object removed. /// If this dictionary is empty. public void Dequeue(out K key, out V value) { var pair = Dequeue(); key = pair.Key; value = pair.Value; } /// /// Adds an object to the PriorityDictionary<, /// >. /// /// The object to add to this PriorityDictionary. /// If item is null. public void Enqueue(K key, V value) { Enqueue(new PriorityQueuePair(key, value)); } /// /// Returns the smallest object in the PriorityDictionary<, /// > without removing it. /// /// If multiple objects are the smallest object, an unspecified one is returned. /// /// The key of the smallest object. /// The value of the smallest object. /// If this dictionary is empty. public void Peek(out K key, out V value) { var pair = Peek(); key = pair.Key; value = pair.Value; } /// /// Stores a value with the key that is used for comparison. /// public sealed class PriorityQueuePair : IComparable { /// /// Retrieves the key of this QueueItem. /// public K Key { get; } /// /// Retrieves the value of this QueueItem. /// public V Value { get; } /// /// Creates a new priority queue pair. /// /// The item key. /// The item value. public PriorityQueuePair(K key, V value) { if (key == null) throw new ArgumentNullException(nameof(key)); Key = key; Value = value; } public int CompareTo(PriorityQueuePair other) { if (other == null) throw new ArgumentNullException(nameof(other)); return Key.CompareTo(other.Key); } public override bool Equals(object obj) { return obj is PriorityQueuePair other && other.Key.Equals(Key); } public override int GetHashCode() { return Key.GetHashCode(); } public override string ToString() { return "PriorityQueueItem[key=" + Key + ",value=" + Value + "]"; } } } }