Create a system to simulate vehicles at an intersection. Assume that there is on
ID: 3572897 • Letter: C
Question
Create a system to simulate vehicles at an intersection. Assume that there is only one lane going in each of four directions, with stop lights facing each direction. Vary the arrival times of each vehicle in each direction and the frequency of lights changes to view the behavior.
So far, I have a method that asks the user for the start and end times of the simulation, as well as the frequency of the light changes. I'm having trouble starting on the traffic light and car generator and am not sure how to go about it.
Explanation / Answer
import java.util.*;
public class VehicleIntersection
{
private final static int PROCESS = 3;
private final static int SIM_LENGTH = 1000;
public static void main(String[] args)
{
Car car = new Car();
Deque<Car> carQueue = new LinkedList<Car>();
int delayTotal = 0, carArrival, lightChange = 0, switchCount = 0, changeCount = 0;
double carCount;
boolean even = false;
String lightColor, green = null, red = null;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the car arrival interval between 1 to 5 sec." + " ");
carArrival = scan.nextInt();
if (!(carArrival < 6 && carArrival > 0))
System.out.println("Enter a valid time." + " ");
Scanner sc = new Scanner(System.in);
System.out.println("Enter in a traffic light duration between 5 to 10 seconds ");
lightChange = sc.nextInt();
if (!(lightChange < 11 && lightChange > 4))
System.out.println("Not a valid time. Enter valid time" + " ");
for (int i = 0; i < SIM_LENGTH; i+= carArrival)
{
carQueue.add(car);
}
for (int i = 0; i < SIM_LENGTH; i++)
{
if (i % lightChange == 0)
{
changeCount++;
}
}
if (changeCount % 2 == 0)
{
even = true;
}
if (even)
{
lightColor = green;
}
else
{
lightColor = red;
}
while (lightColor == green)
{
for (int i = 0; i < SIM_LENGTH; i+= PROCESS)
{
carQueue.remove(car);
}
switchCount++;
}
delayTotal += lightChange;
carCount = (lightChange / PROCESS) * switchCount;
int delayAverage = delayTotal/switchCount;
int stranded = carQueue.size();
System.out.println("Cars across: " + carCount);
System.out.println("Delay (tot): " + delayTotal);
System.out.println("Delay (avg): " + delayAverage);
System.out.println("Number stranded: " + stranded);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.