Write a method called randomWalk that performs steps of a random one-dimensional walk. The random walk should begin at position 0. On each step, you should either increase or decrease the position by 1 (each with equal probability). Your code should continue making steps until a position of 3 or -3 is reached, and then report the maximum position that was reached during the walk. The output should look like the following:
position = 1
position = 0
position = –1
position = –2
position = –1
position = –2
position = –3
max position = 1
package indefinite_loops;
import java.util.Random;
public class RandomWalk {
public void randomWalk() {
// start postion with 0
int position = 0;
Random random = new Random();
// set max postion as 0
int maxPosition = 0;
// condition to make sure this won't break till postion reaches either 3 or -3
while (!((position == 3) || (position == -3))) {
// guess 1 or 2 with 1/2 probability
int guess = random.nextInt(2) + 1;
if (guess == 1)
position -= 1;
else
position += 1;
// print current postion
System.out.println("position = " + position);
// update the max position with each iterate
if (position > maxPosition)
maxPosition = position;
}
// System.out.println("position = " +position);
System.out.println("max position = " + maxPosition);
}
public static void main(String[] args) {
// call our method
new RandomWalk().randomWalk();
}
}
Output:
position = 0
position = -1
position = -2
position = -1
position = 0
position = 1
position = 2
position = 1
position = 2
position = 3
max position = 3