有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java解决方案问题

问题

我正在编写一个代码,模拟一只狗在城市里行走——试图逃离城市。狗以相同的概率在每个十字路口随机选择去哪条路。如果陷入死胡同,狗会直接回到大城市的中心,重新开始。这只狗会一次又一次地这样做,直到它离开城市,或者经过多次试验后感到疲劳。但是当狗每次尝试都从中间(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个排列,但没有一个给出所需的输出。因此,我的结论是,我的代码中的问题


共 (1) 个答案