如何优化此代码以使其更快

2019年3月30日 28点热度 0条评论

我真的是Java的noobie高中生,真的很新,我们目前正在优化一个项目,但现在我被困住了。我认为我已无能为力了。
以下是我的3个课程。
PS,这些代码可以打印出while循环所花费的时间,而我正尝试将其减少到计算机上不到1秒的时间。目前运行在1.49和1.38之间。

主要:

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();
    }
}

小猫.java:

导入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)));
}

}

kittybox.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);
    }
}

但是我仍然无法将代码加速到基准测试。有什么办法可以更快吗?

非常感谢。

解决方案如下:

您可以选择:

Math.random()//它具有可靠的efficiency

您可以参考以下程序:

        int max = 5; 
        int min = 1; 
        int range = max - min + 1; 

        // generate random numbers within 1 to 10 
        for (int i = 0; i < max; i++) { 
            int rand = (int)(Math.random() * range) + min; 

            // Output is different everytime this code is executed 
            System.out.println(rand); 
        }