Max Jacobs
Max Jacobs

Reputation: 13

2D Random walk program with squared distance

I need to create a program which simulates a random walker that takes n steps while printing the location at each step and finally the squared distance from the origin (x^2 + y^2) at the end. I feel like I'm doing something wrong because the squared distance at the end doesn't print the correct value, and I'm lost. Any help?

public class RandomWalker {

    public static void main(String[] args) {

    int steps = Integer.parseInt(args[0]);

    int x = 0;
    int y = 0;

    for (int i = 0; i < steps; i++){
        System.out.println("(" + x + "," + y + ")");
        double z = (int)(Math.random()*4); 
        if (z == 0) {
            x++;
        } else if (z == 1){
            y++;
        } else if (z == 2){
            x--;
        } else if (z == 3){ 
            y--;
        }

    }

    double sqd = (x*x) + (y*y);
    System.out.println("Squared distance = ");
    System.out.println(sqd);

    }
}

The expected output should look something like this:

(0,0)
(-1,0)
(-1,-1)
(-1,-2)
(-1,-3)
(-1,-4)
(-1,-5)
(0,-5)
(-1,-5)
(-2,-5)
(-2,-4)
Squared distance = 
20.0

The outputted squared distance is almost never right, however:

(0,0)
(0,-1)
(0,-2)
(0,-1)
(-1,-1)
(-2,-1)
(-3,-1)
(-3,0)
(-4,0)
(-4,1)
Squared distance = 
10.0

Upvotes: 1

Views: 590

Answers (1)

samgak
samgak

Reputation: 24417

The problem is that you are doing one more iteration of your random walk after you print out the last pair of values, because the println statement is at the beginning of your loop. Put it at the end and the Squared distance will match the last co-ordinate pair that you output:

for (int i = 0; i < steps; i++){
    double z = (int)(Math.random()*4); 
    if (z == 0) {
        x++;
    } else if (z == 1){
        y++;
    } else if (z == 2){
        x--;
    } else if (z == 3){ 
        y--;
    }
    System.out.println("(" + x + "," + y + ")");        
}

You can solve these sorts of issues by stepping through your program with a debugger and inspecting the variable values.

Upvotes: 2

Related Questions