RandomWalker.java


This is the syntax highlighted version of RandomWalker.java from 2.3 Conditionals, Loops of
Introduction to Computer Science by Robert Sedgewick and Kevin Wayne.

/*************************************************************************
 *  Compilation:  javac RandomWalker.java
 *  Execution:    java RandomWalker N
 *  
 *  Simulates how many steps it takes a random walker starting at the
 *  center of a circle of radius N.
 *
 *************************************************************************/

public class RandomWalker { 

   public static void main(String[] args) {
      int N = Integer.parseInt(args[0]);

      int x = 0;       // starting x position
      int y = 0;       // starting y position
      double r;

      // repeat until Euclidean distance is at least N
      int steps = 0;
      while (x*x + y*y <= N*N) {
         steps++;
         r = Math.random();
         if      (r <= 0.25) x++;
         else if (r <= 0.50) x--;
         else if (r <= 0.75) y++;
         else if (r <= 1.00) y--;
      }

      System.out.println(steps);
   }

}


Last updated: Fri Jul 30 16:00:04 EDT 2004 .
Copyright © 2004, Robert Sedgewick and Kevin Wayne.