Java Reference
In-Depth Information
At each value of the clock, the method sees whether the current customer is still being served and
whether a new customer has arrived. If a new customer arrives, the method creates a new customer
object, assigns it a random transaction time, and places the customer into the queue. If a customer is still
being served, the clock advances; if not, a customer leaves the front of the queue and begins service. At
this point, the time the customer waited is noted. Figure 10-6 provides an example of the queue for a por-
tion of the simulation.
The following pseudocode describes the method simulate . It assumes that the class WaitLine has
initialized its data fields as follows: line is an empty queue, and numberOfArrivals , numberServed ,
and totalTimeWaited are each zero.
Algorithm simulate(duration, arrivalProbability, maxTransactionTime)
transactionTimeLeft = 0
for (clock = 0; clock < duration; clock++)
{
if ( a new customer arrives )
{
numberOfArrivals++
transactionTime = a random time that does not exceed maxTransactionTime
nextArrival = a new customer containing clock , transactionTime , and
a customer number that is numberOfArrivals
line.enqueue(nextArrival)
}
if (transactionTimeLeft > 0) // if present customer is still being served
transactionTimeLeft--
else if (!line.isEmpty())
{
nextCustomer = line.dequeue()
transactionTimeLeft = nextCustomer.getTransactionTime() - 1
timeWaited = clock - nextCustomer.getArrivalTime()
totalTimeWaited = totalTimeWaited + timeWaited
numberServed++
}
}
Question 2 Consider the simulation begun in Figure 10-6.
a.
At what time does Customer 4 finish and depart?
b.
How long does Customer 5 wait before beginning the transaction?
10.8
Implementation details for simulate . At each value of the clock, simulate must determine
whether a new customer has arrived. To do so, it needs the probability that a customer will arrive.
This arrival probability is a parameter of the method and has a value between 0 and 1. For exam-
ple, if there is a 65 percent chance that a customer will arrive at any given time, the arrival prob-
ability is 0.65. We then generate a random number between 0 and 1 by using the method random
in Java's class Math . If the value returned by Math.random() is less than the given arrival proba-
bility, simulate creates a new customer and places it into the queue.
The method assigns to each new customer a random transaction time. Given a maximum value
for this time, we can multiply it by Math.random() to get a random transaction time. Adding 1 to the
result ensures that the transaction time is never 0 but allows a small chance that the transaction time
will exceed the given maximum value by 1. For simplicity, we will tolerate this small imprecision.
 
Search WWH ::




Custom Search