Wednesday, February 25, 2015

Random Walkers java in a pgm



RandomWalkers.java

public class RandomWalkers
{
              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;               
        double r;
        boolean[][] visited = new boolean[N][N]; 

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

                    while (cellsToVisit > 0)
        {
            steps++;

           
            for (int i = 0; i < N; i++)
            {
                r = Math.random();
                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 && !visited[x[i]][y[i]])
               {
                    cellsToVisit--;
                    visited[x[i]][y[i]] = true;
                }
            }
        }

        System.out.println(steps);
    }
}

No comments:

Post a Comment