Question: A walker, starting from coordinates (0, 0) has an equal chance of traveling north, east, south, or west for each step they take. Given an

A walker, starting from coordinates (0, 0) has an equal chance of traveling north, east, south, or west for each step they take. Given an input of amount of steps, calculate the new coordinates for each step, along with the total distance, at the very end, using the distance formula. I have compiled the following:

public class RandomWalker

{

public static void main(String[] args)

{

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

int x=0;

int y=0;

System.out.println("("+x+", "+y+")");

for (int i=1; i<=n; i++)

{

double r =Math.random();

double s =Math.random();

int a=0;

int b=0;

if(r>=0.4)

a=1;

else

if(s>=0.4)

b=1;

else

if(r<0.4)

a=-1;

else

if(s<0.4)

b=-1;

int x2= x+a;

int y2= y+b;

int xsub=x2-x;

int ysub=y2-y;

double xd= Math.pow(xsub, 2);

double yd=Math.pow(ysub, 2);

double td=xd+yd;

double d=Math.sqrt(td);

x=x+a;

y=y+b;

System.out.println("("+x+","+y+")");

System.out.println(d);

}

}

}

Yet cannot get the distance, "double d" to be outside, after the loop, and print once, at the end, instead of after every step. Also I can't get the final distance to show as a double value. Or the starting distance, which is also just (0, 0). Any guidance would be appreciated.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!