I am a really really new noobie high school student in java and we're currently optimizing a project but I'm stuck now. I think I've down everything I can do. Below are my 3 classes. PS, These codes print out the time spent in while loop and I'm trying to get it down to less than 1 sec on my computer. It's running between 1.49 and 1.38 currently.
main:
public class code {
public static void main(String[] args) {
int numRows = 30;
int numCols = 30;
int start = 31;
int exit = 868;
int numKittens = 30_000;
KittenBox box = new KittenBox(numRows, numCols, start, exit,
numKittens);
double a = 10;
box.play();
}
}
kitten.java:
import java.util.SplittableRandom;
public class Kitten {
private int rows;
private int columns;
public int square;
private SplittableRandom a;
public Kitten(int rows, int columns, int square) {
this.rows = rows;
this.columns = columns;
this.square = square;
a = new SplittableRandom();
}
public int move() {
int i = a.nextInt(1, 5);
return (i == 1 && (!(this.square < columns))) ?
this.square -= rows : ((i == 2 && (!(this.square >= columns *
(rows - 1)))) ? this.square += rows : ((i == 3 && (!(this.square
% rows == 0))) ? this.square -= 1 : ((!(this.square % rows ==
rows - 1)) ? this.square += 1 : this.square)));
}
}
kittenbox.java:
public class KittenBox {
private ArrayList<Kitten> kitten;
private int numRows;
private int numCols;
private int start;
private int exit;
private int numKittens;
public KittenBox(int numRows, int numCols, int start, int exit, int numKittens) {
this.numRows = numRows;
this.numCols = numCols;
this.start = start;
this.exit = exit;
this.numKittens = numKittens;
kitten = new ArrayList<>();
}
public void play() {
for (int i = 0; i < numKittens; i++) {
kitten.add(new Kitten(numRows, numCols, start));
}
long startTime = System.nanoTime();
while (!kitten.isEmpty()) {
for (int i = 0; i < kitten.size(); i++) {
kitten.get(i).move();
if (kitten.get(i).square == exit) {
kitten.remove(i);
}
}
}
long endTime = System.nanoTime();
System.out.format("Kittens took %f seconds to escape.\n",
(endTime - startTime) / 1000000000.0);
}
}
but I still can't speed my code up to the benchmark. is there any way that's faster?
thanks a lot.