gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 18:26:34 25 4
gpt4 key购买 nike

我是一名真正的java菜鸟高中生,我们目前正在优化一个项目,但我现在陷入困境。我想我已经放下了我能做的一切。以下是我的 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)));
}

}

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

但我仍然无法将我的代码加速到基准。有没有更快的方法?

非常感谢。

最佳答案

您可以选择:

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

关于java - 如何优化此代码以使其更快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60220417/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com