gpt4 book ai didi

java - 在 0,0 坐标处启动 Random Walker java 程序时遇到问题

转载 作者:行者123 更新时间:2023-12-02 08:53:29 25 4
gpt4 key购买 nike

我正在尝试构建一个程序,该程序采用整数并模拟随机游走的运动,直到随机游走者距起点位于曼哈顿距离 r 处。关键要求之一是在 0,0 坐标处启动程序,但我无法

public class RandomWalker {

public static void main(String args[]) {

int r = Integer.parseInt(args[0]);

int x = 0;
int y = 0;
int step = 0;
double R;
while(Math.abs(x) < r && Math.abs(y) < r) {
step++;
R = Math.random();
if(R <= 0.25) x++;
else if (R <= 0.50) x--;
else if (R <= 0.75) y++;
else if (R <= 1.00) y--;

System.out.println("(" + x + ", " + y + ")" );
}
System.out.println("steps = " + step);
}
}

最佳答案

我怀疑你只需要在步进之前打印坐标即可。见下文。我还尝试将 walker 值封装在类中而不是 main 方法中。

public class RandomWalker {
private final Random random;
private int steps = 0;
private int x = 0;
private int y = 0;

public RandomWalker(Random random) {
this.random = random;
}

public String toString() {
return steps + ": (" + x + "," + y + ")";
}

public void step() {
steps++;
switch (random.nextInt(4)) {
case 0: x++; break;
case 1: x--; break;
case 2: y++; break;
case 3: y--; break;
}
}

public int distance() {
return Math.abs(x) + Math.abs(y);
}

public static void main(String args[]) {
int r = Integer.parseInt(args[0]);
RandomWalker walker = new RandomWalker(new Random());
while (walker.distance() < r) {
System.out.println(walker);
walker.step();
}
System.out.println("steps = " + walker.steps);
}
}

关于java - 在 0,0 坐标处启动 Random Walker java 程序时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60628349/

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