问题
我正在编写一个代码,我正在模拟一条狗在城市中行走 - 试图逃离城市。狗在每个路口以相等的概率随机选择走哪条路。如果卡在死胡同,狗会直接回到大城市的中心,重新开始。狗会一次又一次地这样做,直到它离开城市,或者直到它经过 T 次试验后感到疲倦。但是当狗在每次尝试中再次从中间(N/2,N/2)开始时,它会忘记它在上一次尝试中访问过的所有交叉点。
主意
这个想法是模仿我们教科书中给出的代码并提出解决方案。我们得到输入 N, T - 其中 N 是城市中南北向和东西向街道的数量,T 是狗在放弃之前试图离开城市的次数。我们必须使用 StdDraw 将其绘制出来。我们已经学会了如何进行随机运动 -生成一个介于 0 和 4 之间的数字 - 上:0 右:1 下:2 左:3
我的方法
import java.util.Random;
public class RandomWalk {
private static final Random RNG = new Random (Long.getLong ("seed",
System.nanoTime()));
public static void main(String[] args) {
int N = Integer.parseInt(args[0]); // lattice size
int T = Integer.parseInt(args[1]); // number of trials
int deadEnds = 0; // trials resulting in a dead end
StdDraw.setCanvasSize();
StdDraw.setXscale(0,N);
StdDraw.setYscale(0,N);
// simulate T self-avoiding walks
for (int t = 0; t < T; t++) {
StdDraw.clear();
StdDraw.setPenRadius(0.002);
StdDraw.setPenColor(StdDraw.LIGHT_GRAY);
for(int i=0;i<N;i++){
StdDraw.line(i, 0, i, N);
StdDraw.line(0, i, N, i);
}
StdDraw.setPenColor(StdDraw.RED);
StdDraw.setPenRadius(0.01);
boolean[][] a = new boolean[N][N]; // intersections visited
int x = N/2, y = N/2; // current position
// repeatedly take a random step, unless you've already escaped
while (x > 0 && x < N-1 && y > 0 && y < N-1) {
int t_x = x;
int t_y=y;
// dead-end, so break out of loop
if (a[x-1][y] && a[x+1][y] && a[x][y-1] && a[x][y+1]) {
deadEnds++;
break;
}
// mark (x, y) as visited
a[x][y] = true;
// take a random step to unvisited neighbor
int r = RNG.nextInt(4);
if (r ==3) {
//move left
if (!a[x-1][y])
t_x--;
}
else if (r == 1 ) {
//move right
if (!a[x+1][y])
t_x++;
}
else if (r == 2) {
//move down
if (!a[x][y-1])
t_y--;
}
else if (r == 0) {
//move up
if (!a[x][y+1])
t_y++;
}
StdDraw.line(t_x, t_y, x, y);
x = t_x;
y = t_y;
}
System.out.println("T: "+t);
}
System.out.println(100*deadEnds/T + "% dead ends");
}
}
问题
给定 N - 15, T - 10, -Dseed=5463786 我们应该得到类似的输出 - http://postimg.org/image/s5iekbkpf/
我得到了 - 见http://postimg.org/image/nxipit0pp/
我不知道我哪里错了。我知道这在本质上是非常具体的,但我真的很困惑我做错了什么。我尝试了 0、1、2、3 的所有 24 种排列,但没有一个给出所需的输出。因此,我得出结论,我的代码中存在问题。