dimanche 24 septembre 2017

2D random walk fill all cells (java)

Simulate how many steps its take a random walker starting at the center of an 10x10 grid to visit every cell of the grid. If the walker tries to go outside of the grid then it doesn't move in that step. Write a java program which simulates th steps of the random walker, and keeps hold about the grid with 2D boolean array and write out the steps when the random walker have walked all the cells.

But I have two problems. The walker seems to walk outside of the array/grid.

And it keeps counting the steps when it walks outside of the grid.

The code should not count the step when he tries to go outside of the grid. Any idea how I can fix it?

The code I've come up with so far is:

public class RandomWalk { 

public static void main(String[] args) {
    int n = Integer.parseInt(args[0]);
    int[] x = new int[n];
    int[] y = new int[n];
    int cellsToVisit = n*n;
    int steps = 0;
    boolean[][] a = new boolean[n][n];

    for(int i = 0; i < n; i++) {
        x[i] = n/2;
        y[i] = n/2;
    }
    a[n/2][n/2] = true;
    cellsToVisit--;

    while (ctv > 0) {

        double r = Math.random();
        for(int i = 0; i < n; i++) {
            if(r < 0.25){ 
                x[i]--;
            } else if(r < 0.50){
                x[i]++;
            } else if(r < 0.75){ 
                y[i]--;
            } else if(r < 1.00){ 
                y[i]++;
            }

            if(x[i] < n && y[i] < n && x[i] >= 0 && y[i] >= 0 && !a[x[i]][y[i]]) {
                cellsToVisit--;
                fylki[x[i]][y[i]] = true;          
            }

            steps++;
           System.out.println(cellsToVisit + "     " + steps + "    " + x[i] + " " + y[i]); 
        }
    }
    System.out.println(steps);
}

}




Aucun commentaire:

Enregistrer un commentaire