// Create a PriorityQueue that holds any object that // implements an IPrioritizable interface. static void Main(string[] args) { // Set the number of priority levels we're using. int numPriorities = 5; // Create a priority queue. // Note that we instantiate the PQ for IPrioritizable objects! PriorityQueue <IPrioritizable> pq = new PriorityQueue <IPrioritizable>(numPriorities); // Create a random number (0 - 50) of random // packages and parcels; add them to the priority queue. IPrioritizable pack; PackageFactory fact = new PackageFactory(); // We want a random number less than 50. Random rand = new Random(); // Get a random int from 0 - 50. int numToCreate = rand.Next(50); Trace.WriteLine("TRACE: Creating 50 packages"); Console.WriteLine("Receiving packages:"); for (int i = 0; i < numToCreate; i++) { // Generate a random package. pack = fact.CreatePackage(numPriorities); Trace.WriteLine( String.Format("\received a {0}", pack.ToString())); Console.WriteLine( "\tReceived package {0}: a {1}", i, pack.ToString()); // Add it to the priority queue. pq.Enqueue(pack); } // See what we got. Trace.WriteLine( String.Format("Received {0} packages", pq.Count)); Console.WriteLine("Packages received: {0}", pq.Count); Console.WriteLine("\tList:"); // Display packages with priorities and ToAddresses. // Uses new PriorityQueue.GetEnumerator() foreach (IPrioritizable ip in pq) { if (ip != null) { Console.WriteLine("\t\ta {0} sent to {1}", ip.ToString(), ((IPackage)ip).ToAddress); // The parentheses above ensure that we first // extract the item, then convert it to IPackage, // and finally call ToAddress(), which would be // illegal this way: (IPackage)ip.ToAddress() } } // "Ship" all packages. int totalShipped = 0; Trace.WriteLine("TRACE: Before shipping, count = " + pq.Count); Console.WriteLine("\tshipping all packages (in priority order, of course):"); int numToShip = pq.Count; // Dequeue the correct number of packages. // Another way to iterate the PriorityQueue. for (int i = 0; i < numToShip; i++) { IPrioritizable ipack = pq.Dequeue(); if (ipack != null) { // Note you can call ToString() on any object, don't // need a cast for this one. Console.WriteLine("\tShipped a {0}", ipack.ToString()); ++totalShipped; } Trace.WriteLine( String.Format("TRACE: Main() with {0} items to go", pq.Count)); } // See how many we "shipped." Console.WriteLine("Shipped {0} packages", totalShipped); Trace.WriteLine( String.Format("TRACE: Terminating after shipping {0} packages", totalShipped)); // Wait for user to acknowledge the results. Console.WriteLine("Press Enter to terminate..."); Console.Read(); }
public int CompareTo(IPrioritizable other) { return(Priority.CompareTo(other?.Priority ?? int.MaxValue)); }