Random2DWalk.java


Below is the syntax highlighted version of Random2DWalk.java from §1.3 Conditionals and Loops.


/*************************************************************************
 *  Compilation:  javac Random2DWalk.java
 *  Execution:    java Random2DWalk N
 *  
 *  Simulates a random walk on a 2 dimensional grid. At each step you
 *  either move left, right, up, or down 1 unit. Prints out how far
 *  away from the origin you end up after N steps.
 *
 *  Sample execution:
 * 
 *     % java Random2DWalk 1000000
 *      Arrives at (817, 435) after 1000000 steps.
 *      Distance from origin = 925.5884614665418
 *
 *  Remark: on average, after N steps you are sqrt(N) units from origin.
 *
 *************************************************************************/

public class Random2DWalk {

   public static void main(String[] args) { 

      int N = Integer.parseInt(args[0]);         // number of steps
      int x = 0, y = 0;                          // current location

      for (int i = 0; i < N; i++) {
         double r = Math.random();               // between 0.0 and 1.0
         if      (r < 0.25) x++;
         else if (r < 0.50) x--;
         else if (r < 0.75) y++;
         else               y--;
      }

      System.out.println("Arrives at (" + x + ", " + y + ") after " + N + " steps.");
      System.out.println("Distance from origin = " + Math.sqrt(x * x + y * y));
   }
}


Copyright © 2007, Robert Sedgewick and Kevin Wayne.
Last updated: Tue Sep 29 16:17:41 EDT 2009.