Data Structures for Java William H Ford William

  • Slides: 78
Download presentation
Data Structures for Java William H. Ford William R. Topp Chapter 15 Queues and

Data Structures for Java William H. Ford William R. Topp Chapter 15 Queues and Priority Queues Bret Ford © 2005, Prentice Hall © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Queue Collection • A queue is a list of items that allows for access

Queue Collection • A queue is a list of items that allows for access only at the two ends of the sequence, called the front and back of the queue. An item enters at the back and exits from the front. • • A waiting line at a grocery store or a bank is a model of a stack. © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Queue Operations • Queue operations are restricted to the ends of the list, called

Queue Operations • Queue operations are restricted to the ends of the list, called front and back. push(item) adds item at the back pop() removes element from the front peek() accesses value at the front © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Queue Operations (cont) • An item removed (pop) from the queue is the first

Queue Operations (cont) • An item removed (pop) from the queue is the first element that was added (push) into the queue. A queue has FIFO (first-in-first-out) ordering. • Queue inserts followed by queue deletions maintain the order of the elements © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Queue Interface • The generic Queue interface defines a restricted set of collection operations

Queue Interface • The generic Queue interface defines a restricted set of collection operations that access and update elements only at the end of the list. © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Queue Interface (concluded) © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All

Queue Interface (concluded) © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Linked. Queue Class • The Queue interface is an adapter which defines a restricted

Linked. Queue Class • The Queue interface is an adapter which defines a restricted set of list methods. A Queue class can be efficiently implemented using a linked list as the storage structure. The Linked. Queue class uses a Linked. List collection and composition. © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Linked. Queue Class (continued) public class Linked. Queue<T> implements Queue<T> { private Linked. List<T>

Linked. Queue Class (continued) public class Linked. Queue<T> implements Queue<T> { private Linked. List<T> qlist = null; public Linked. Queue () { qlist = new Linked. List<T>(); }. . . } © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Implementing Linked. Queue Method pop() • Method has runtime efficiency O(1) public T pop()

Implementing Linked. Queue Method pop() • Method has runtime efficiency O(1) public T pop() { // if the queue is empty, throw // No. Such. Element. Exception if (is. Empty()) throw new No. Such. Element. Exception( "Linked. Queue pop(): queue empty"); // remove and return the first element in the list return qlist. remove. First(); } © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Program 15. 1 • The program implements an interview scheduler that is a queue

Program 15. 1 • The program implements an interview scheduler that is a queue of Time 24 objects. Output lists the times and the potential length of each interview. © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Program 15. 1 (continued) import java. io. *; java. util. Scanner; ds. util. Linked.

Program 15. 1 (continued) import java. io. *; java. util. Scanner; ds. util. Linked. Queue; ds. time. Time 24; public class Program 15_1 { public static void main(String[] args) throws IOException { final Time 24 END_DAY = new Time 24(17, 00); String appt. Str; // time interval from current appt to next appt Time 24 appt. Time = null, interview. Time = null; // input stream to read times as strings from // file "appt. dat" Scanner input = new Scanner( new File. Reader("appt. dat")); © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Program 15. 1 (continued) // queue to hold appointment time // for job applicants

Program 15. 1 (continued) // queue to hold appointment time // for job applicants Linked. Queue<Time 24> appt. Q = new Linked. Queue<Time 24>(); // construct the queue by appt times as // strings from file; use parse. Time to // convert to Time 24 object while (input. has. Next()) { appt. Str = input. next. Line(); appt. Q. push(Time 24. parse. Time(appt. Str)); } // output the day's appointment schedule System. out. println("Appointment Interview"); © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Program 15. 1 (continued) // pop next appt time and determine // available time

Program 15. 1 (continued) // pop next appt time and determine // available time for interview (peek // at next appt at front of queue) while (!appt. Q. is. Empty()) { // get the next appointment appt. Time = appt. Q. pop(); // interview time is interval to next // appt or to END_DAY if (!appt. Q. is. Empty()) interview. Time = appt. Time. interval( appt. Q. peek()); else interview. Time = appt. Time. interval(END_DAY); © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Program 15. 1 (concluded) // display appointment time and interview time System. out. println("

Program 15. 1 (concluded) // display appointment time and interview time System. out. println(" " + appt. Time + " " + interview. Time); } } } © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Program 15. 1 (Run) File "appt. dat": 10: 00 11: 15 13: 00 13:

Program 15. 1 (Run) File "appt. dat": 10: 00 11: 15 13: 00 13: 45 14: 30 15: 30 16: 30 Run: Appointment 10: 00 11: 15 13: 00 13: 45 14: 30 15: 30 16: 30 Interview 1: 15 1: 45 0: 45 1: 00 0: 30 © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Radix Sort • The radix sort is a linear algorithm that sorts an array

Radix Sort • The radix sort is a linear algorithm that sorts an array of integers. It uses successive digits in the numbers to partially sort the list. • Successive elements in the array are passed into an array of ten queues (index 0 to 9) using a digit as the index. Elements are copied from the array back to the array, creating a partially sorted list. © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Radix Sort Example • List: [91, 6, 85, 15, 92, 35, 30, 22, 39]

Radix Sort Example • List: [91, 6, 85, 15, 92, 35, 30, 22, 39] After Pass 0: [30, 91, 92, 22, 85, 15, 35, 6, 39] After Pass 2: [6, 15, 22, 30, 35, 39, 85, 91, 92] © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Radix Sort (continued) • Any two numbers with different ten's digits, such as 35

Radix Sort (continued) • Any two numbers with different ten's digits, such as 35 and 92 will be in the proper relative order since the algorithm collects numbers from the 3 -bin before numbers from the 9 -bin. • Pass 0 assures the ordering of numbers with the same tens digit. Such numbers will appear in the tens queue in order of their ones digit. © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Radix Sort (continued) Initial sequence: {91, 6, 85, 15, 92, 35, 30, 22, 39}

Radix Sort (continued) Initial sequence: {91, 6, 85, 15, 92, 35, 30, 22, 39} Same tens digit. In order by ones digit © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Radix Sort Method • The radix. Sort() method uses the expanded base 10 representation

Radix Sort Method • The radix. Sort() method uses the expanded base 10 representation of a number. value = xd-110 d-1 + xd-210 d-2 +. . . + x 2102 + x 1101 + x 0100 • The implementation uses 10 queues // allocate 10 null references to a Linked. Queue[] digit. Queue = new Linked. Queue[10]; // initialize each element of digit. Queue to be // an empty queue for (i=0; i < digit. Queue. length; i++) digit. Queue[i] = new Linked. Queue(); © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Radix Sort Method (continued) • The radix. Sort() method must execute d iterations, one

Radix Sort Method (continued) • The radix. Sort() method must execute d iterations, one for each digit. The i-th iteration distributes the numbers into the array of queues, digit. Queue, by using the digit corresponding to the power 10 i. To determine the value of the digit at any position i, divide a number by the power = 10 i and take the remainder after division by 10. digit. Queue[(arr[i] / power) % 10]. push(new Integer(arr[i])); © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Radix Sort distribute() // support method for radix. Sort() // distribute array elements into

Radix Sort distribute() // support method for radix. Sort() // distribute array elements into one of 10 queues // using the digit corresponding to power // power = 1 ==> 1's digit // power = 10 ==> 10's digit // power = 100 ==> 100's digit //. . . private static void distribute(int[] arr, Linked. Queue[] digit. Queue, int power) { int i; // loop through the array, inserting each // element into the queue (arr[i] / power) % 10 for (i = 0; i < arr. length; i++) digit. Queue[(arr[i] / power) % 10]. push(arr[i]); } © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Radix Sort collect() // support method for radix. Sort() // gather elements from the

Radix Sort collect() // support method for radix. Sort() // gather elements from the queues and copy // back to the array private static void collect( Linked. Queue[] digit. Queue, int[] arr) { int i = 0, digit; // scan the array of queues using // indices 0, 1, 2, etc. for (digit = 0; digit < 10; digit++) // collect items until queue empty // and copy items back to the array while (!digit. Queue[digit]. is. Empty()) { arr[i] = digit. Queue[digit]. pop()); i++; } } © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

radix. Sort() Method public static void radix. Sort(int[] arr, int d) { int i;

radix. Sort() Method public static void radix. Sort(int[] arr, int d) { int i; // current digit found by dividing by 10^power int power = 1; // allocate 10 null references to a Linked. Queue[] digit. Queue = new Linked. Queue[10]; // initialize each element of digit. Queue to be // an empty queue for (i=0; i < digit. Queue. length; i++) digit. Queue[i] = new Linked. Queue(); for (i=0; i < d; i++) { distribute(arr, digit. Queue, power); collect(digit. Queue, arr); power *= 10; } } © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

radix. Sort() Method (concluded) n Runtime efficiency of radix. Sort() is O(dn) where the

radix. Sort() Method (concluded) n Runtime efficiency of radix. Sort() is O(dn) where the array has n elements and the maximum integer has d digits. © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Program 15. 2 • The program illustrates radix. Sort() for an array of 50

Program 15. 2 • The program illustrates radix. Sort() for an array of 50 integers in the range 0 -99, 999. © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Program 15. 2 (continued) import java. util. Random; import ds. util. Arrays; public class

Program 15. 2 (continued) import java. util. Random; import ds. util. Arrays; public class Program 15_2 { public static void main(String[] args) { // array to hold the data that is sorted int[] arr = new int[50]; Random rnd = new Random(); int i; // initialize array with 50 random numbers in // range 0 - 99999 for (i = 0; i < 50; i++) arr[i] = rnd. next. Int(100000); // apply the radix sort and output // the sorted array Arrays. radix. Sort(arr, 5); display. Array(arr); } © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Program 15. 2 (continued) private static void display. Array(int[] arr) { int i, j,

Program 15. 2 (continued) private static void display. Array(int[] arr) { int i, j, strn. Length; String s, strn; for (i=0; i < arr. length; i++) { // represent value of arr[i] as a string strn = String. value. Of(arr[i]); // capture the length of strn. Length = strn. length(); s = ""; // justify strn in a field // of 8 print positions for (j=0; j < 8 -strn. Length; j++) s += " "; s += strn; © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Program 15. 2 (concluded) // output the justified integer value System. out. print(s); //

Program 15. 2 (concluded) // output the justified integer value System. out. print(s); // newline every 6 numbers if ((i+1) % 6 == 0) System. out. println(); } } © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Program 15. 2 (Run) RUN 2554 16483 28922 36705 54797 65465 80185 90076 97332

Program 15. 2 (Run) RUN 2554 16483 28922 36705 54797 65465 80185 90076 97332 3097 20040 29730 36867 55577 68416 80659 90717 98616 5231 23202 30672 47340 56055 68935 81371 93637 6876 24353 32032 47688 59553 71586 83443 94948 8539 24758 32198 51547 61588 73017 87678 95470 © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved. 12446 25996 32261 53617 65289 77119 88138 96984

Bounded Queue • A bounded queue is a queue that can contain a fixed

Bounded Queue • A bounded queue is a queue that can contain a fixed number of elements. An insert into the queue can occur only when the queue is not already full. • The BQueue class implements a bounded queue. The class implements the Queue interface. The boolean method full() indicates whether the queue is full. • The class uses an array to store the elements. © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

BQueue Class API © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All

BQueue Class API © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

BQueue Class Example • The example illustrates the declaration of a BQueue object and

BQueue Class Example • The example illustrates the declaration of a BQueue object and the use of full() to avoid attempting an insertion into a full queue. An exception occurs when we call push() from within a try block and attempt to add an element to a full queue. © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

BQueue Class Example (continued) // declare an empty bounded queue with fixed size 15

BQueue Class Example (continued) // declare an empty bounded queue with fixed size 15 BQueue<Integer> q = new BQueue<Integer>(15); int i; // fill-up the queue for (i=1; !q. full(); i++) q. push(i); // output element at the front of q and the queue size System. out. println(q. peek() + " " + q. size()); try { q. push(40); // exception occurs } catch (Index. Out. Of. Bounds. Exception iobe) { System. out. println(iobe); } © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

BQueue Class Example (concluded) Output: 1 15 java. lang. Index. Out. Of. Bounds. Exception:

BQueue Class Example (concluded) Output: 1 15 java. lang. Index. Out. Of. Bounds. Exception: BQueue push(): queue full © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

BQueue Class public class BQueue<T> implements Queue<T> { // array holding the queue elements

BQueue Class public class BQueue<T> implements Queue<T> { // array holding the queue elements private T[] queue. Array; // index of the front and back of the queue private int qfront, qback; // the capacity of the queue and the current size private int qcapacity, qcount; // create an empty bounded queue with specified size public BQueue(int size) { qcapacity = size; queue. Array = (T[])new Object[qcapacity]; qfront = 0; qback = 0; qcount = 0; } © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

BQueue Class (concluded) public BQueue() { // called non-default constructor // with capacity =

BQueue Class (concluded) public BQueue() { // called non-default constructor // with capacity = 50 BQueue(50); } < method full() and methods in the Queue interface > } © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

BQueue Class Implementation No room for E. Need a way to use the slots

BQueue Class Implementation No room for E. Need a way to use the slots at indices 0, 1. © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

BQueue Class Implementation (continued) • Think of the queue as a circular sequence with

BQueue Class Implementation (continued) • Think of the queue as a circular sequence with a series of slots that allow element to enter in a clockwise fashion. The element at index qfront exits the queue and an element enters the queue at index qback. © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

BQueue Class Implementation (continued) • Treating the array as a circular sequence involves updating

BQueue Class Implementation (continued) • Treating the array as a circular sequence involves updating qfront and qback to cycle back to the front the array as soon as they move past the end of the array. Move qback forward: qback = (qback + 1) % qcapacity; Move qfront forward: qfront = (qfront + 1) % qcapacity; © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

BQueue Class full() public boolean full() { return qcount == qcapacity; } © 2005

BQueue Class full() public boolean full() { return qcount == qcapacity; } © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

BQueue Class push() public void push(T item) { // is queue full? if so,

BQueue Class push() public void push(T item) { // is queue full? if so, throw an // Index. Out. Of. Bounds. Exception if (qcount == qcapacity) throw new Index. Out. Of. Bounds. Exception( "BQueue push(): queue full"); // insert into the circular queue. Array[qback] = item; qback = (qback+1) % qcapacity; // increment the queue size qcount++; } © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

BQueue Class pop() public T pop() { // if queue is empty, throw a

BQueue Class pop() public T pop() { // if queue is empty, throw a // No. Such. Element. Exception if (count == 0) throw new No. Such. Element. Exception( "BQueue pop(): empty queue"); // save the front of the queue T queue. Front = queue. Array[qfront]; // perform a circular queue deletion qfront = (qfront+1) % qcapacity; // decrement the queue size qcount--; // return the front return queue. Front; } © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Priority Queue Collection • A priority queue is a collection in which all elements

Priority Queue Collection • A priority queue is a collection in which all elements have a comparison (priority) ordering. • It provides only simple access and update operations where a deletion always removes the element of highest priority © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

PQueue Interface • The generic PQueue resembles a queue with the same method names.

PQueue Interface • The generic PQueue resembles a queue with the same method names. © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

PQueue Interface (concluded) © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All

PQueue Interface (concluded) © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Heap. PQueue Class • The collection class Heap. PQueue implements the PQueue interface. –

Heap. PQueue Class • The collection class Heap. PQueue implements the PQueue interface. – By default, the element of highest priority is the one with the largest value (a maximum priority queue); that is, if x and y are two elements in a priority queue and x > y, then x has higher priority than y. © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Heap. PQueue Class Example // create an empty priority queue of generic type String

Heap. PQueue Class Example // create an empty priority queue of generic type String Heap. PQueue<String> pq = new Heap. PQueue<String>(); int n; pq. push("green"); pq. push("red"); pq. push("blue"); // output the size and element with the highest priority System. out. println(pq. size() + " " + pq. peek()); // use pop() to clear the collection and list elements in // priority (descending) order while (!pq. is. Empty()) System. out. print(pq. pop() + " "); Output: 3 red green blue © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Support Services Pool • The application processes job requests to a company support service

Support Services Pool • The application processes job requests to a company support service pool. A request has a job ID, a job status, and a time requirement. • Job. Status is an enum with a listing of employee categories with values that allows for comparison of objects. • The Job. Request class implements Comparable and describes job objects. • © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Support Services Pool (continued) enum Job. Status { clerk (0), manager (1), director(2), president(3);

Support Services Pool (continued) enum Job. Status { clerk (0), manager (1), director(2), president(3); int js. Value; Job. Status(int value) { js. Value = value; } public int value() { return js. Value; } } © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Support Services Pool (continued) © 2005 Pearson Education, Inc. , Upper Saddle River, NJ.

Support Services Pool (continued) © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Support Services Pool (continued) © 2005 Pearson Education, Inc. , Upper Saddle River, NJ.

Support Services Pool (continued) © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Program 15. 3 • The program processes job requests with different employee statuses. Output

Program 15. 3 • The program processes job requests with different employee statuses. Output lists the jobs by status along with their total time. © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Program 15. 3 (continued) import java. io. *; import java. util. Scanner; import ds.

Program 15. 3 (continued) import java. io. *; import java. util. Scanner; import ds. util. Heap. PQueue; public class Program 15_3 { public static void main(String[] args) throws IOException { // handle job requests Heap. PQueue<Job. Request> job. Pool = new Heap. PQueue<Job. Request>(); // job requests are read from file "job. dat" Scanner sc = new Scanner(new File. Reader( "job. dat")); © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Program 15. 3 (continued) // time spent working for each category // of employee

Program 15. 3 (continued) // time spent working for each category // of employee // initial time 0 for each category int[] job. Services. Use = {0, 0, 0, 0}; Job. Request job = null; // read file; insert each job into // priority queue while ((job = Job. Request. read. Job(sc)) != null) job. Pool. push(job); // delete jobs from priority queue // and output information System. out. println("Category Job ID" + " Job Time"); © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Program 15. 3 (continued) while (!job. Pool. is. Empty()) { // remove a job

Program 15. 3 (continued) while (!job. Pool. is. Empty()) { // remove a job from the priority // queue and output it job = (Job. Request)job. Pool. pop(); System. out. println(job); // accumulate job time for the // category of employee job. Services. Use[job. get. Status(). value()] += job. get. Job. Time(); } System. out. println(); write. Job. Summary(job. Services. Use); } © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Program 15. 3 (concluded) private static void write. Job. Summary( int[] job. Services. Use)

Program 15. 3 (concluded) private static void write. Job. Summary( int[] job. Services. Use) { System. out. println("Total Pool Usage"); System. out. println(" President " + job. Services. Use[3]); System. out. println(" Director " + job. Services. Use[2]); System. out. println(" Manager " + job. Services. Use[1]); System. out. println(" Clerk " + job. Services. Use[0]); } } © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Program 15. 3 (Run) Run Category President Director Manager Clerk Job ID 303 306

Program 15. 3 (Run) Run Category President Director Manager Clerk Job ID 303 306 300 307 310 302 311 304 305 308 309 301 Job Time 25 50 20 70 60 40 30 10 40 20 20 30 Total Pool Usage President 75 Director 190 Manager 80 Clerk 70© 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Event-Driven Simulation • An event-driven simulation uses a priority queue to store events that

Event-Driven Simulation • An event-driven simulation uses a priority queue to store events that occur over time as the simulation unfolds. • The bank simulation looks a stream of customers that are served by two tellers. Different event types deal with arrival, service, and departure of a customer. Arrival times and service times are random. © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Event-Driven Simulation (continued) • The graphic illustrates events (Ai = arrival, Si = service,

Event-Driven Simulation (continued) • The graphic illustrates events (Ai = arrival, Si = service, Di = departure) for four customers. Solid line is service and dotted line is waiting time. © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Event Classes • Event classes are defined in an inheritance hierarchy. The abstract base

Event Classes • Event classes are defined in an inheritance hierarchy. The abstract base class Event compares the time events occurs and defines the method do. Event() which is implemented in each subclass. © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Event Class public abstract class Event implements Comparable<Event> { protected int time; // constructor

Event Class public abstract class Event implements Comparable<Event> { protected int time; // constructor sets time for the event public Event(int t) { time = t; } abstract void do. Event(); // describes activity © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Event Class (concluded) // used to order the events (elements) // in a priority

Event Class (concluded) // used to order the events (elements) // in a priority queue public int compare. To(Event e) { if(time < e. time) return -1; else if (time == e. time) return 0; else return 1; } } © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Event. Driven. Simulation Class import ds. util. Heap. PQueue; public class Event. Driven. Simulation

Event. Driven. Simulation Class import ds. util. Heap. PQueue; public class Event. Driven. Simulation { // minimum heap pops event elements // in order of their time private Heap. PQueue<Event> event. Queue = new Heap. PQueue<Event>(new Less<Event>()); // adds an Event object to the queue public void push. Event(Event e) { event. Queue. push(e); } © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Event. Driven. Simulation Class (concluded) // runs simulation by processing events // as they

Event. Driven. Simulation Class (concluded) // runs simulation by processing events // as they exit the priority queue public void run() { while (!event. Queue. is. Empty()) { // extract event and process it // with do. Event() Event next. Event = event. Queue. pop(); next. Event. do. Event(); } } } © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Bank. Simulation Class public class Bank. Simulation extends Event. Driven. Simulation { // parameters

Bank. Simulation Class public class Bank. Simulation extends Event. Driven. Simulation { // parameters used to describe the simulation int simulation. Length; // simulation length int num. Tellers; int arrival. Low, arrival. High; // next arrival range int service. Low, service. High; // service range // variables used to monitor the simulation int num. Customers = 0; int total. Wait. Time = 0; // used for delay between arrivals int prev. Arr. Time = 0; // detail each event? boolean verbose. Run = false; // use for random times Random rnd = new Random(); // list of tellers Teller[] t. List = null; © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Bank. Simulation Class (concluded) // key method inputs parameters, creates events, // runs simulation

Bank. Simulation Class (concluded) // key method inputs parameters, creates events, // runs simulation and outputs results public void start. Simulation() {. . . } } © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

start. Simulation() public void start. Simulation() { // read simulation parameters from keyboard input.

start. Simulation() public void start. Simulation() { // read simulation parameters from keyboard input. Parameters(); // create instances for each teller; // for convenience, tellers are referenced // with indices beginning at 1 for (int i = 1; i <= num. Tellers; i++) t. List[i] = new Teller(); © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

start. Simulation() (continued) // for the length of the simulation, create // successive arrival

start. Simulation() (continued) // for the length of the simulation, create // successive arrival events at random arrival // times; push events on the priority queue // and update prev. Arr. Time int t = 0; while (t < simulation. Length) { // random. Time() returns random integer // in the range arrival. Low to arrival. High t += random. Time(arrival. Low, arrival. High); if (t >= simulation. Length) break; // create an arrival event and add it // to priority queue push. Event(new Arrival. Event(t, prev. Arr. Time)); // update prev. Arr. Time for use by next arrival prev. Arr. Time = t; } © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

start. Simulation() (concluded) // with arrival events loaded in the priority // queue, begin

start. Simulation() (concluded) // with arrival events loaded in the priority // queue, begin execution of the simulation; // Note: during execution, the queue will // dynamically grow since when an arrival event // exits the queue, its do. Event() method adds // a service event to the queue; when a service // event exits the queue, its do. Event() method // adds a departure event run(); // display a summary of results display. Results(); } © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Arrival. Event Class private class Arrival. Event extends Event { private int elapsed. Time;

Arrival. Event Class private class Arrival. Event extends Event { private int elapsed. Time; public Arrival. Event(int time, int prev. Arr. Time) { super(time); elapsed. Time = time - prev. Arr. Time; } public void do. Event() { int i, min. Teller, service. Time; Decimal. Format number. Fmt = new Decimal. Format("00"); // increment number of customers num. Customers++; © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Arrival. Event Class (continued) // use elapsed. Time to update back. Service // for

Arrival. Event Class (continued) // use elapsed. Time to update back. Service // for each teller; return teller with // minimum back. Service; this is the next // available teller min. Teller = min. Teller. Service(t. List, elapsed. Time); // back. Service for teller is wait // time for customer total. Wait. Time += t. List[min. Teller]. back. Service; // generate service time for customer; // add to back. Service for min. Teller who // will serve customer service. Time = random. Time(service. Low, service. High); t. List[min. Teller]. back. Service += service. Time; © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Arrival. Event Class (continued) if (verbose. Run). . . // create Service. Event object

Arrival. Event Class (continued) if (verbose. Run). . . // create Service. Event object and add // to priority queue push. Event(new Service. Event( time + t. List[min. Teller]. back. Service, num. Customers, min. Teller, service. Time)); } private int min. Teller. Service(Teller[] t. List, int elapsed. Time) { int i, min. Teller = 1; © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Arrival. Event Class (concluded) for (i = 1; i <= num. Tellers; i++) t.

Arrival. Event Class (concluded) for (i = 1; i <= num. Tellers; i++) t. List[i]. back. Service = (t. List[i]. back. Service elapsed. Time <= 0) ? 0 : t. List[i]. back. Service - elapsed. Time; for (i = 2; i <= num. Tellers; i++) if (t. List[i]. back. Service < t. List[min. Teller]. back. Service) min. Teller = i; return min. Teller; } } © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Program 15. 4 public class Program 15_4 { public static void main(String[] args) {

Program 15. 4 public class Program 15_4 { public static void main(String[] args) { // create bank simulation object and start it up Bank. Simulation bank = new Bank. Simulation(); bank. start. Simulation(); } } © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Program 15. 4 (Run #1) Run 1: Use verbose run ('Y' or 'N'): Y

Program 15. 4 (Run #1) Run 1: Use verbose run ('Y' or 'N'): Y Enter the simulation time in minutes: 40 Enter number of available tellers: 2 Enter range of potential arrival times: 3 7 Enter range of potential service times: 5 11 Customer Customer Customer #01 #02 #01 #03 #02 #04 #03 #02 Arrival 6 Wait 6 Begin service at 12 by teller 1 Service time 6 Arrival 13 Wait 8 Departs 18 Served by 1 Arrival 18 Wait 8 Begin service at 21 by teller 1 Service time 8 Arrival 22 Wait 11 Begin service at 26 by teller 2 Service time 8 Departs 29 Served by 1 © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Program 15. 4 (Run #1, concluded) Customer Customer Customer #05 #04 #03 #06 #05

Program 15. 4 (Run #1, concluded) Customer Customer Customer #05 #04 #03 #06 #05 #06 #04 #05 #06 Arrival 29 Wait 9 Begin service at 33 by teller 1 Service time 11 Departs 34 Served by 2 Arrival 36 Wait 6 Begin service at 38 by teller 2 Service time 9 Begin service at 42 by teller 1 Service time 6 Departs 44 Served by 1 Departs 47 Served by 2 Departs 48 Served by 1 Simulation Summary Number of customers is 6 Average waiting time is 0. 0 minutes Service time for tellers Teller 1: Busy 64. 6% Overtime 8 Teller 2: Busy 36. 2% Overtime 7 © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Program 15. 4 (Run #2) Run 2: Use verbose run ('Y' or 'N'): N

Program 15. 4 (Run #2) Run 2: Use verbose run ('Y' or 'N'): N Enter the simulation time in minutes: 480 Enter number of available tellers: 3 Enter range of potential arrival times: 1 5 Enter range of potential service times: 4 11 Simulation Summary Number of customers is 156 Average waiting time is 1. 0 minutes Service time for tellers Teller 1: Busy 88. 4% Overtime 12 Teller 2: Busy 80. 0% Overtime 10 Teller 3: Busy 65. 3% Overtime 19 © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.