49.9k views
4 votes
Two-dimensional random walk (20 points). A two-dimensional random walk simulates the behavior of a particle moving in a grid of points. At each step, the random walker moves north, south, east, or west with probability equal to 1/4, independent of previous moves. Write a program RandomWalker.java that takes an int command-line argument n and simulates the motion of a random walk for n steps. Print the location at each step (including the starting point), treating the starting point as the origin (0, 0). Also, print the square of the final squared Euclidean distance from the origin as double. Note: you do not need arrays for this problem, just keep track of the x and y coordinates during the random walk.

1 Answer

3 votes

Answer:

The following code in the explanation does the job for you. Here I have made use of Random class of Java to generate random numbers.

Step-by-step explanation:

Code:

import java.util.*;

class RandomWalker {

public static void main(String args[]){

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

int x = 0;

int y = 0;

Random random = new Random();

for(int i = 0; i < n; i++){

int tmp = random.nextInt(4);

if(tmp == 0){

x++;

}

if(tmp == 1){

y++;

}

if(tmp == 2){

y--;

}

if(tmp == 3){

x--;

}

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

}

int distance = x*x + y*y;

System.out.println("Squared Distance = " + distance);

}

}

Two-dimensional random walk (20 points). A two-dimensional random walk simulates the-example-1
Two-dimensional random walk (20 points). A two-dimensional random walk simulates the-example-2
Two-dimensional random walk (20 points). A two-dimensional random walk simulates the-example-3
User Botond Kopacz
by
4.7k points