RandomWalk.java


This is the syntax highlighted version of RandomWalk.java from 2.4 Input and Output of
Introduction to Computer Science by Robert Sedgewick and Kevin Wayne.

/*************************************************************************
 *  Compilation:  javac RandomWalk.java
 *  Execution:    java RandomWalk N
 *  Dependencies: StdDraw.java
 *
 *  % java RandomWalk 20
 *  total steps = 300
 *
 *  % java RandomWalk 50
 *  total steps = 2630
 *
 *  Simulates a 2D random walk and plots the trajectory.
 *
 *  Remarks: works best if N is a divisor of 600.
 *
 *************************************************************************/

import java.awt.Color;

public class RandomWalk { 

    public static void main(String[] args) {
        int N = Integer.parseInt(args[0]);
        StdDraw.create(600, 600);
        StdDraw.setScale(-N, -N, +N, +N);
        StdDraw.clear(Color.gray);
        int x = 0, y = 0;
        StdDraw.go(x, y);

        int steps = 0;
        while (Math.abs(x) < N && Math.abs(y) < N) {
            StdDraw.setColor(Color.white);
            StdDraw.spot(0.9, 0.9);
            double 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++;
            steps++;
            StdDraw.setColor(Color.blue);
            StdDraw.go(x, y);
            StdDraw.spot(0.9, 0.9);
            StdDraw.pause(40);
        }
        System.out.println("Total steps = " + steps);
    }

}



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