RandomWalk解决方案问题

时间:2015-09-18 02:06:56

标签: java random stddraw

问题

我正在编写一个代码,我正在模拟一只在城市中行走的狗 - 试图逃离城市。狗随机选择在每个交叉路口以相同的概率前往哪个方向。如果卡在死胡同,狗将直接回到大城市的中间并重新开始。狗会一次又一次地这样做,直到它离开城市或直到它在T次试验后累了。但是当狗在每次尝试中从中间(N / 2,N / 2)再次开始时,它将忘记它在之前的尝试中访问过的所有交叉点。

IDEA

这个想法是模仿我们教科书中给出的代码并提出解决方案。我们得到了输入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/

我不知道我哪里错了。我知道这本质上是非常具体的,但我真的很困惑,因为我做错了。我尝试了所有24个0,1,2,3的排列,但没有一个给出了所需的输出。所以,我在我的代码中总结了这个问题。

1 个答案:

答案 0 :(得分:0)

检查你的StdDraw.java:

http://introcs.cs.princeton.edu/java/stdlib/StdDraw.java.html

你的代码应该没问题,我得到了预期的结果