/** This class performs a simple traffic simulation. */ import java.util.Random; public class A8Simulation { /** Conducts a simple simulation of a highway intersection with a traffic light. Uses a Simulator object to keep track of the traffic and average waiting time in each direction, and overall. Each simulation runs for a fixed number of cycles, where a cycle consists of a green light in the east-west direction (and a red light in the north-south direction) for a given number of seconds, followed by a green light in the north-south direction (and a red light in the east-west direction) for a given number of seconds. At each second of the simulation, the traffic light is red in one direction. A vehicle moving in the direction may or may not arrive at this second. There is a specified probability that such a vehicle will arrive during that second. This probability for north or south bound traffic may from the probability for east or west bound traffic. Traffic that gets a green light is not simulated. @param sim the Simulator object @param r a random number generator for the simulation of vehicle arrivals */ /* During each cycle of the simulation, the traffic light turns red in the N-S direction, and the time when it will turn green is computed. Then for each second that the light is red, it is determined whether a vehicle has arrived. If so, an arrival message is sent to the simulator object. In any case, the time counter is incremented. When the light turns green in the N-S direction, a similar computation is performed for E-W traffic. The traffic light is not explicitly represented. */ public static void simulate(Simulator sim, Random r) { // the total number of cycles in the simulation int NUMBER_OF_CYCLES = 20; // length of the red light for N-S traffic int NS_WAITING_TIME = 40; // length of the red light for E-W traffic int EW_WAITING_TIME = 50; // The probability that a north or south bound vehicle will // arrive at a red light at any given second // (when it is red) double NS_PROBABILITY_OF_ARRIVAL = 0.08; // The probability that an east or west bound vehicle will // arrive at a red light at any given second // (when it is red) double EW_PROBABILITY_OF_ARRIVAL = 0.10; // Possible values of the flag that is sent to the simulator // to tell it the direction of the arriving vehicle // Used to avoid magic numbers (or magic booleans) boolean IS_GOING_NS = true; boolean IS_GOING_EW = false; // time in seconds since the beginning of the simulation int seconds = 0; // time of the next light change int departureTime = 0; // the simulation proper for (int i=0; isimulate method to perform two brief simulations of traffic. @param args is ignored */ public static void main(String[] args) { Random r = new Random(8); Simulator sim = new Simulator(); simulate(sim,r); printResults(sim); System.out.println(); sim.reset(); simulate(sim,r); printResults(sim); } }