/****************************************************************************** * 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)); } }