Remove 2 beans from the bag.
If:
They are both black return one of them to the bag and discard
the other.
One is black and the other white return the white bean to the bag
and discard the black bean
Both are white discard both and put a black bean in the bag
What color is the last bean?
You decide to write a program that you can run for 50 simulations.
Start with a bag of 10 beans and continue running the program
incrementing the number of beans in the bag by one until you have
tested for a bag with 60 beans. Fill the bag with random colors of
beans and with draw the beans from the bag on a random basis, as well.
Run the simulation and print out four columns of numbers:
Number of beans
Number of Black Beans
Number of White Beans
Color of last bean.
Use the ArrayList Class to implement this program. Remove beans from
random positions within the array and add beans back in a different
random position
Here's What I have done so far:
but it keeps saying that the arraylist is out of bound. I know where the problem is but I don't know how to fix it. If I remove the plus 1 from the line
index1 = rand.nextInt(bag.size() + 1)
it would say negative bound error.
import java.io.*;
import java.util.*;
import java.util.Random;
public class Counter
{
public static void main (String args[])
{
ArrayList<Integer> bag = new ArrayList<Integer>();
Random rand = new Random();
int color;
int index1;
int index2;
int blackCount = 0;
int whiteCount = 0;
String last = "";
System.out.println("Beans Black White Last");
for (int total = 10; total <= 60; total++)
{
for (int run = total; run > 0; run--)
{
// 1 black and 2 white
color = rand.nextInt(2) + 1;
if (color == 1)
{
blackCount++;
}
else if (color == 2)
{
whiteCount++;
}
bag.add(rand.nextInt(bag.size() + 1), color);
}
System.out.print(total + "\t " + blackCount + "\t " + whiteCount + "\t ");
while (blackCount != 1 || whiteCount != 1)
{
index1 = rand.nextInt(bag.size());
index2 = rand.nextInt(bag.size());
if (bag.get(index1) == 1 && bag.get(index2) == 1)
{
bag.remove(index2);
blackCount--;
}
else if (bag.get(index1) == 1 && bag.get(index2) == 2)
{
bag.remove(index1);
blackCount--;
}
else if (bag.get(index1) == 2 && bag.get(index2) == 1)
{
bag.remove(index2);
blackCount--;
}
else if (bag.get(index1) == 2 && bag.get(index2) == 2)
{
bag.remove(index1);
index2 = rand.nextInt(bag.size());
while (bag.get(index2) == 1)
{
if (bag.get(index2) == 1)
{
index2 = rand.nextInt(bag.size());
}
}
bag.remove(index2);
bag.add(rand.nextInt(bag.size() + 1), 1);
blackCount++;
whiteCount -= 2;
}
}
if (whiteCount == 1)
{
last = "White";
}
else
{
last = "Black";
}
System.out.print(last + "\n");
bag.clear();
blackCount = 0;
whiteCount = 0;
}
}
}
Related
I am constructing a simulation of beehive and I make use of a 2D array called workerBee.
It has the following 6 fields: beeId, Age, Type(egg = 1, larva = 2, pupa = 3, worker = 4, drone = 5), PollenCollection, Eaten, Alive
Brief about the model: The Queen Bee lays eggs daily(10 to 50 eggs) and they are added to the hive.Each day, data about the bees are updated(their age and type).
For every day that passes, I print the beehive status which prints information about the number of bees, births, deaths etc..
For some days during the simulation(at the beginning, say day 6 to 10), the number of larva reported is around 800 to 900 for 1 day.
Here are the codes that deal with the printing and counting:
public static int layDailyEggs() {
Random randomEggs = new Random();
final int MAX_EGGS = 50;
final int MIN_EGGS = 10;
int x = randomEggs.nextInt((MAX_EGGS - MIN_EGGS) + 1) + MIN_EGGS;
eggsLaid = x;//eggsLaid as a global variable to be used in printBeehiveStatus
return x;//To pass as argument to addEggToHive
}
public static void addEggToHive(int eggsLaid) {
//Update the workerBee array with available slots
//Traverse the 2D array and while beeId != 0, add eggs and update
for (int i = 0; i < workerBee.length; i++) {
if (workerBee[i][0] == 0 && eggsLaid > 0) {
//Available space
workerBee[i][0] = i;//Update beeID
workerBee[i][1] = 1;//Update age
workerBee[i][2] = 1;//Update Type
eggsLaid--;
}
}
}
public static void countTypesOfBees() {
//Initialize for each day
totalEggsLaid = 0;
numberOfBirths = 0;
numberOfLarva = 0;
numberOfPupa = 0;
numberOfWorkerBees = 0;
numberOfDrones = 0;
//To call upon updating type of each bee
for (int i = 0; i < workerBee.length; i++) {
if(workerBee[i][2] == 1) {
totalEggsLaid++;
}else if(workerBee[i][2] == 2) {
numberOfLarva++;
numberOfBirths++;
}else if(workerBee[i][2] == 3) {
numberOfPupa++;
numberOfBirths++;
}else if(workerBee[i][2] == 4) {
numberOfWorkerBees++;
numberOfBirths++;
}else if(workerBee[i][2] == 5) {
numberOfDrones++;
numberOfBirths++;
}
}
}
//Method called once daily
public static void metamorphose() {
numberOfDeaths = 0;
Random random = new Random();
for (int i = 0; i < workerBee.length; i++) {
//Updating the type of bee based on age of Bee
if(workerBee[i][1] == 4) {
workerBee[i][2] = 2;
}else if (workerBee[i][1] == 10) {
workerBee[i][2] = 3;
}else if(workerBee[i][1] == 20){
//Probability for a drone to emerge is 10%(As per area under curve, should be less than or equal to 10%)
double probability = random.nextDouble();
if (probability <= 0.1) {
workerBee[i][2] = 5;//Drone Bee
}else{
workerBee[i][2] = 4;//Worker Bee
}
}
if (workerBee[i][1] == 35 || workerBee[i][1] == 56) {
//Call a funeral
funeral(i);
numberOfDeaths++;
}
}
countTypesOfBees();
}
//To be called at the end of the day
public static void printBeehiveStatus() {
System.out.print("Queen laid " + eggsLaid + " eggs!" +
"\nBeehive status\nEgg Count: "+ totalEggsLaid + "\nLarva Count: " + numberOfLarva + "\nPupa Count: " + numberOfPupa +
"\nWorker Count: "+ numberOfWorkerBees + "\nDrone Count: " + numberOfDrones +
"\nDeath Count: " + numberOfDeaths + "\nBirth Count: "+ numberOfBirths +
"\nHoney Stock: " + honeyStock +"\n");
printFlowerGarden();
}
The index of the fields of the workerBee array are in the order specified above.
The order which which they are executed each day are as follows(Note that they are not the complete set)
addEggToHive(layDailyEggs());
incrementAge();
metamorphose();
printBeehiveStatus();
Screenshot [1]: https://i.stack.imgur.com/qTeuo.png
Screenshot [2]: https://i.stack.imgur.com/eMsHq.png
Note
The eggs hatches into larva when it is 4 days old
If there is anything else that you think might be causing the problem, tell me I'll upload that part of the code.
Found the solution.
Actually, the method incrementAge() was supposed to increase the ages of all bees in the hive by 1 each day. However, I was simply incrementing all ages in the array without checking whether that particular row is an actual bee or not as I had initialized unused rows to 0
i wanted to do the guess the number game. For one round my programm works and I can guess a number. I want that the user can enter the amout of rounds (1-20) what he wants to play, but there is my problem this isn't working as thought. I tried to use a boolean but after I guessed the number for 1 round it doesn't begin the next round.
The In function is similar to scanner, but I have a java class for that therefore I use that.
public class GuessNumber {
public static void main(String[] args) {
System.out.println("round 1-20");
int roundTyped = In.readInt();
int rndN = (int) (Math.random()*100)+1;
int typedN = 0;
int trys = 0;
boolean active = true;
int round = 0;
while (active) {
while (typedN != rndN) {
trys++;
System.out.println(trys + ". Versuch:");
typedN = In.readInt();
if(typedN < 1 || typedN > 100) {
System.out.println("ungueltig");
}else if(typedN < rndN) {
System.out.println("groesser");
}else if(typedN > rndN) {
System.out.println("kleiner");
}else if(typedN == rndN) {
System.out.println("korrrekt");
}
}
round++;
if (round == roundTyped) {
active = false;
}
}
}
You set the number to be guessed only once at the start of the program. Therefore, after the user has guessed the correct number once, the remaining rounds will all be completed instantly (the condition of the inner while will always be true).
I would suggest you use a debugger to find problems like these. When you step through your program, it will immediately become obvious what is happening.
Having two while loops is unnecessary, you can put several conditions for the while, and you use 2 variables that will be the same round and trys.
But your biggest problem is that you actually set your active to false right before checking if it is true.
Try something like that :)
System.out.println("round 1-20");
int roundTyped = In.readInt();
int rndN = (int) (Math.random()*100)+1;
int typedN = 0;
int nTrysAllowed = 10; // The max number of tries
int trys = 0;
int round = 0;
while (round < roundTyped) {
while (typedN != rndN && trys < nTrysAllowed) {
trys++;
System.out.println(trys + ". Versuch:");
typedN = In.readInt();
if(typedN<1 || typedN >100) {
System.out.println("ungueltig");
} else if(typedN < rndN) {
System.out.println("groesser");
} else if(typedN > rndN) {
System.out.println("kleiner");
} else {
System.out.println("korrrekt");
}
}
// Here you can reduce the max number of tries for example or do whatever you want. For example:
round++;
if (typedN == rndN) {
// New number to guess
rndN = (int) (Math.random()*100)+1;
// Difficulty
nTrysAllowed--;
trys = 0;
} else {
System.out.println("Game done you can't go to next round, you lose this one.");
round = roundTyped;
}
}
import processing.core.PApplet;
import static java.lang.System.out;
public class GoL2 extends PApplet {
int rectSideLength = 25; // rectSideLength = length of each side of the rectangles drawn that represent cells
int generation = 0;
int windowWidth = 1920;
int windowHeight = 950;
int[][] currentGeneration = new int[windowWidth][windowHeight]; // currentGeneration = 2D array to gold cell values of current generation
int[][] nextGeneration = new int[windowWidth][windowHeight]; // nextGeneration = 2D array to hold cell values of next generation
int sumOfNeighbors;
int temporarySumOfNeighbors;
int counter;
public static void main(String[] args) {
PApplet.main("GoL2");
}
public void settings() {
size(windowWidth, windowHeight);
}
int numRectWidth = width / rectSideLength; // numRectWidth = the number of rectangles wide that will fit in the x axis of window
int numRectHeight = height / rectSideLength; // numRectHeight = the number of rectangles that will fit in the y axis of window
// The previous statements are here because they need the size of the frame to
// be set in order to accurately set the variables, lest they end up equal to 100
/* public void setup() {
* background(255);
* frameRate(1);
* for (int y = 0; y < windowHeight; y++) { // For each row,
* for (int x = 0; x < windowWidth; x++) { // For each element in the current row,
* currentGeneration[x][y] = (int) random(0, 2); // Set element (cell) equal to either 0 or 1 (on or off)
* }
* }
* } */
public void setup() {
background(255);
frameRate(1);
for (int y = 0; y < windowHeight; y++) { // For each row,
for (int x = 0; x < windowWidth; x++) { // For each element in the current row,
currentGeneration[x][y] = 0; // Set element (cell) equal to either 0 or 1 (on or off)
}
}
currentGeneration[25][25] = 1;
currentGeneration[25][26] = 1;
currentGeneration[25][27] = 1;
currentGeneration[26][27] = 1;
currentGeneration[27][26] = 1;
}
public void draw() {
numRectWidth = width / rectSideLength;
numRectHeight = height / rectSideLength;
displayCurrentGeneration();
try {
Thread.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
fill(255, 20, 147);
textSize(30);
text(generation, 20, 30);
textSize(10);
text("25,25", 625, 645);
text("24,27", 600, 695);
text(generation, 580, 695);
generation++;
generateNextGeneration();
}
public void displayCurrentGeneration() {
background(255);
for (int y = 0; y < 950; y++) { // For each row,
for (int x = 0; x < 1920; x++) { // For each element in the current row,
if (currentGeneration[x][y] == 0) { // If element equals zero, make rectangle white
fill(255);
stroke(0);
} else if (currentGeneration[x][y] == 1) { // If element equals one, make rectangle black
fill(0);
stroke(255);
} else {
out.println("Inappropriate value for currentGeneration[" + x + "][" + y + "]. Value: "
+ currentGeneration[x][y] + ", generation: " + generation);
}
rect(x * rectSideLength, y * rectSideLength, rectSideLength, rectSideLength); // Display rectangle (cell)
}
}
// out.println("Generation " + generation);
}
public void generateNextGeneration() {
out.println("Generating gen " + generation);
for (int y = 1; y < numRectHeight - 1; y++) { // For each row,
for (int x = 1; x < numRectWidth - 1; x++) { // For each element in the current row,
sumOfNeighbors = 0;
sumOfNeighbors = getSumOfNeighbors(x, y);
if (sumOfNeighbors != 2 && sumOfNeighbors != 3) { // Death
nextGeneration[x][y] = 0;
} else if (sumOfNeighbors == 3 && currentGeneration[x][y] == 0) { // Birth
nextGeneration[x][y] = 1;
} else if ((sumOfNeighbors == 2 || sumOfNeighbors == 3) && currentGeneration[x][y] == 1) { // Stasis
nextGeneration[x][y] = 1;
}
}
}
currentGeneration = nextGeneration.clone();
}
public int getSumOfNeighbors(int xAxis, int yAxis) {
temporarySumOfNeighbors = 0;
for (int i = -1; i < 2; i++) {
for (int j = -1; j < 2; j++) {
if (xAxis == 24 && yAxis == 27 && j != 0 && i != 0) {
out.println("X" + j + ", Y" + i + ":: " + currentGeneration[xAxis + j][yAxis + i]);
} else if (xAxis == 24 && yAxis == 27 && j == 0 && i != 0) {
out.println("X" + ", Y" + i + ":: " + currentGeneration[xAxis + j][yAxis + i]);
} else if (xAxis == 24 && yAxis == 27 && j != 0 && i == 0) {
out.println("X" + j + ", Y" + ":: " + currentGeneration[xAxis + j][yAxis + i]);
} else if (xAxis == 24 && yAxis == 27 && j == 0 && i == 0) {
out.println("X" + ", Y" + ":: " + currentGeneration[xAxis + j][yAxis + i]);
}
temporarySumOfNeighbors += currentGeneration[xAxis + j][yAxis + i];
}
}
temporarySumOfNeighbors -= currentGeneration[xAxis][yAxis];
if (temporarySumOfNeighbors > 8) {
out.println("temporarySumOfNeighbors > 8: " + temporarySumOfNeighbors);
}
if (xAxis == 24 && yAxis == 27) {
out.println("Generation: " + generation + "- " + xAxis + ", " + yAxis + ": " + temporarySumOfNeighbors);
}
return temporarySumOfNeighbors;
}
}
http://pastebin.com/GH51hXzJ
I am a beginner attempting to code the Game of Life, and I am unsure how to find the source of my issues. I set the game to just start with a simple glider in setup, and believe I may have found the effects of the issue.
I put markers on the cells to help track them. If you watch cell (24,27) you will see at least an example of the issue. In the console, I print out the neighborhood of that cell throughout the run of the program. It appears to somehow detect the neighborhood that (24,27) will have in generation 2 in generation 1, and vice versa (assuming that the first generation is generation 0). I am unsure how to explain it, but if you examine the console output and look at the neighborhoods, you see that it detects generation 2's neighborhood in generation 1 and vice versa. That's why when (24,27) has 3 neighbors in generation 1, it only comes to life in generation 3 while in generation 2, it only has 2 neighbors.
Please let me know if you have any questions, I find it difficult to explain my problem.
The issue is explained more here: http://imgur.com/gallery/iRc07/new
Thank you
This is the main source of your problem:
currentGeneration = nextGeneration.clone();
You might think that line will copy everything from nextGeneration into currentGeneration, and it does... but not in the way you're thinking it does.
The nextGeneration variable is a 2D array. In other words, it's an array of arrays. In other other words, the values contained by nextGeneration are arrays.
When you call the clone() function of an array, it copies the values of the old array into a new array. There's your problem: your values are arrays. So it's copying the arrays, not the values inside those second arrays.
Because of that, both nextGeneration and currentGeneration are pointing to the same arrays. So now when you calculate the next generation, you're changing the arrays of the current generation. This doesn't work, since the Game of Life calculation requires two separate arrays.
In other words, you're making a shallow copy of the arrays.
This might be easier to explain with a simpler program:
public class Test {
public static void main(String... args){
//create an array
int[][] array = {{1, 2, 3}, {4, 5, 6}};
//clone the array
int[][] arrayTwo = array.clone();
//change the original array
array[0][0] = 99;
//second array has also changed!
System.out.println(arrayTwo[0][0]);
}
}
Long story short: You should almost never use the clone() function.
You could fix your problem by making a deep copy of the array. There are libraries that handle this for you, or you could use serialization, or just write your own nested for loop.
But an even simpler (and I would argue more correct) solution would be: stop using class-level variables when you don't need them.
The clone() problem wouldn't be a problem, except you're using nextGeneration as a class-level variable. This means that it retains its value between calls to generateNextGeneration(). And since that value is pointing to the arrays inside currentGeneration, that's causing all of the problems.
You already handle this issue with your other variables: notice how you're resetting the sumOfNeighbors and temporarySumOfNeighbors before you use them. You could do the same thing with the nextGeneration variable.
But I would go a step further and get rid of all three of those class-level variables. Move their declarations to inside the functions that use them, that way you don't have to worry about them maintaining their values between function calls.
Two more notes while I'm at it:
You shouldn't really call Thread.sleep() from the draw() function (or any event function). Just set the frame rate and let Processing handle the timing for you.
You're using a ton of cells that you aren't drawing. Your array is 1920x950, but you're only drawing a small percentage of those cells. That's wasting a ton of CPU time on cells you never show. Like I said in your other question, you need to be more careful about distinguishing between pixel coordinates and array coordinates.
Anyway, this was a good question. I think you're getting closer. You just need to get rid of those extra cells and you'll be in pretty good shape. Good luck.
PS: I'm going to add a processing tag to your question. If you have any questions in the future, it's probably a good idea to make sure to include this tag. Otherwise I won't see it. :p
it's my first post so DO stomp me if I wrote something stupid.
I've just started IT classes, and today on "while" loops class my tutor gave us the following homework:
Write a program which reads a natural number n and displays in one graphical box all its divisors from the interval [2; n-1].
So far I came up with a code that works but the result is a bit wrong:
import java.util.Arrays;
import javax.swing.JOptionPane;
public class Divisors {
public static void main(String[] args) {
String n = JOptionPane.showInputDialog(null, "Enter a natural number");
Integer i = Integer.parseInt(n);
int d = i - 1;
int x = 2;
int[] dvr = new int[i]; // [i] because bigger numbers need more iterations
while (x >= 2 && x <= d) {
double y = i % x;
if (y == 0) {
dvr[x] = x;
x = x + 1;
} else {
x = x + 1;
}
}
JOptionPane.showMessageDialog(null, "The divisors of " + i + " are:\n" + Arrays.toString(dvr));
}
}
The problem is that the loop fills the array with a lot of zeroes, and the screenshot of tutor's results shows a window listing only the divisors.
I tried to do this with ArrayList, but that's black magic for me right now and my tutor didn't teach us yet how to use anything beyond stuff used in my code anyway.
Any help highly appreciated.
The main problem you're having is that you're going to have an unknown number of values you want to print, but you're using an array to store them, and arrays have a fixed size. Since you have an array of int, it's going to be entirely populated with the default value of zero.
Ideally, you'd only print the first bunch of non-zero values of your array, but you're storing the divisors scattered throughout your array.
dvr[x] = x; stores each value at an index of that value, when really you should just store each new value into the next open spot in the array.
Create a separate index variable, and store each value using it instead:
int index = 0;
while (x >= 2 && x <= d) {
...
if (y == 0) {
dvr[index++] = x;
...
Then when your main loop is done, you can create a new "display array" that holds only the divisors, and not the zeros. At this point, index tells you exactly how large it needs to be:
int[] display = Arrays.copyOf(dvr, index);
JOptionPane.showMessageDialog(null, "The divisors of " + i + " are:\n" + Arrays.toString(display));
In Java the default value of an int is zero. So that is why you see a lot of zeros.
Since you define the size of the array to be i which is more than what is required as the no of divisors would always be less than i.
So instead of printing the entire array you should only print it up to the total no of divisors for which you should a separate variable instead of using x.
Here is the modified version where I am using a separate index variable to keep track of number of divisors which start from 0. In the end you can just print the array up to the index
import java.util.Arrays;
import javax.swing.JOptionPane;
public class Divisors {
public static void main(String[] args) {
String n = JOptionPane.showInputDialog(null, "Enter a natural number");
Integer i = Integer.parseInt(n);
int d = i - 1;
int index = 0;
int x=2;
int[] dvr = new int[i]; // [i] because bigger numbers need more iterations
while (x >= 2 && x <= d) {
double y = i % x;
if (y == 0) {
dvr[index] = x;
x = x + 1;
index= index + 1;
} else {
x = x + 1;
}
}
JOptionPane.showMessageDialog(null, "The divisors of " + i + " are:\n" + Arrays.copyOfRange(drv, 0, index));
}
}
Set datastructure avoids duplicates, you can use that to overcome the problem of duplicate divisors getting added into the data structure.
import java.util.*;
import javax.swing.JOptionPane;
public class Divisors {
public static void main(String[] args) {
String n = JOptionPane.showInputDialog(null, "Enter a natural number");
Integer i = Integer.parseInt(n);
int d = i - 1;
int x = 2;
Set<Integer> divisors = new HashSet<>();
while (x >= 2 && x <= d) {
double y = i % x;
if (y == 0) {
divisors.add(x);
x = x + 1;
} else {
x = x + 1;
}
}
List<Integer> l = new ArrayList<>(divisors);
JOptionPane.showMessageDialog(null, "The divisors of " + i + " are:\n" + l);
}
}
Use ArrayList to create Dynamic Array.
Below Code will help you.
Things to change In your Program.
import java.util.*;
take an ArrayList varible
call toString method on Arraylist Object
import java.util.*;
import javax.swing.JOptionPane;
public class NewClass3 {
public static void main(String[] args) {
String n = JOptionPane.showInputDialog(null, "Enter a natural number");
Integer i = Integer.parseInt(n);
int d = i - 1;
int x = 2;
List<Integer> dvr = new ArrayList<>();
while (x >= 2 && x <= d) {
double y = i % x;
if (y == 0) {
dvr.add(x);
x=x+1;
} else {
x = x + 1;
}
}
JOptionPane.showMessageDialog(null, "The divisors of " + i + " are:\n" + dvr.toString());
}
}
I am working on a class assignment that has us create a system to simulate vehicles at an intersection. We are to assume that there is one lane going in each of four directions, with stoplights facing each direction. We have to vary the arrival average of vehicles in each direction and the frequency of the light changes to view the "behavior" of the intersection.
I gave my best attempt at the assignment, but still being new to Java I seem to have made a mistake that I am taking a very long time trying to figure out. Basically, my outputs at the bottom of the program do not output anything.
I am also currently stuck assuming that the outputs will output what I am desiring them to, which obviously would require the rest of my code to be sound.
That being said, if anyone can spot my error that is preventing my code from outputting everything, or anything in addition that catches your eye, then I would be very appreciative.
import java.util.*;
public class Intersection
{
private final static int PROCESS = 3;
private final static int SIM_LENGTH = 1000;
#SuppressWarnings("resource")
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 in a car arrival interval between 1 and 5 seconds." + "\n");
carArrival = scan.nextInt();
if (!(carArrival < 6 && carArrival > 0))
System.out.println("Enter a valid time." + "\n");
Scanner sc = new Scanner(System.in);
System.out.println("Enter in a traffic light duration between 5 and 10 seconds." + "\n");
lightChange = sc.nextInt();
if (!(lightChange < 11 && lightChange > 4))
System.out.println("Enter a valid time." + "\n");
//add a car to the queue every [carArrival] seconds
for (int i = 0; i < SIM_LENGTH; i+= carArrival)
{
carQueue.add(car);
}
//Develop a way for the program to know that SIM_LENGTH has
//counted 'lightChange' seconds.
//Count each time lightChange occurs
for (int i = 0; i < SIM_LENGTH; i++)
{
if (i % lightChange == 0)
{
changeCount++;
}
}
//Assuming light starts as red, every time the preceding count increases by 1,
//switch lightColor.
//if count % 2 == 0, return green light; else red light
if (changeCount % 2 == 0)
{
even = true;
}
if (even)
{
lightColor = green;
}
else
{
lightColor = red;
}
while (lightColor == green)
{
//remove a car from the queue every [PROCESS] seconds
//(PROCESS is time to pass intersection)
for (int i = 0; i < SIM_LENGTH; i+= PROCESS)
{
carQueue.remove(car);
}
//I increment 'switchCount so I can use it as a divisor
//for delayTotal to find the delayAverage
switchCount++;
}
//Trying to increment delay time (cars are immobilized by red light)
delayTotal += lightChange;
//carCount Example:
//lightChange = 6; PROCESS = 3; switchCount =166.7 times
//carCount = 333.4 cars; obviously I need it to a whole number
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);
}
}