M
M
mk_qwerty2019-10-22 21:14:40
Java
mk_qwerty, 2019-10-22 21:14:40

How to apply "random walks without self-intersections" model in java?

Good day, I can not find an error in the program. The program returns 0 in each case.
The essence of the task: the program receives command line arguments n and trials and simulates random walks without self-intersections on an NxN grid. The result of the calculation is the percentage of walks that ended in a dead end.

public class selfAvoidingWalk{
  public static void main(String[] args){
    int n = Integer.parseInt(args[0]);
    int trials = Integer.parseInt(args[1]);
    int deadEnds = 0;

    for (int t = 0; t < trials; t++){
      boolean[][] a = new boolean[n][n];
      int x = n/2;
      int y = n/2;

      while ((x > 0) && (x < (n-1)) && (y > 0) && (y > (n-1))){
        a[x][y] = true;

        if (a[x-1][y] && a[x+1][y] && a[x][y-1] && a[x][y+1]){
            deadEnds++;
            break;
        }

        double r = Math.random();
        if (r < 0.25){
          if (!a[x+1][y]) x++;
        }
        else if (r < 0.50){
          if (!a[x-1][y]) x--;
        }
        else if (r < 0.75){
          if (!a[x][y+1]) y++;
        }
        else if (r < 1.00){
          if (!a[x][y-1]) y--;
        }

      }
    }

    //System.out.println(deadEnds);
    System.out.println(100*deadEnds/trials + "% dead ends");
  }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman, 2019-10-22
@mk_qwerty

can't find error

Condition in while...
int y = n/2;
... 
&& (y > (n-1))
always false.
because (n / 2) <= (n - 1)
int deadEnds = 0;
... 
100*deadEnds/trials == 0
0/n = 0
https://rextester.com/CQOHTE74063

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question