Write a method randomWalk that performs a random one-dimensional walk, reporting
ID: 3724338 • Letter: W
Question
Write a method randomWalk that performs a random one-dimensional walk, reporting each position reached and the maximum position reached during the walk. The random walk should begin at position 0. On each step, you should either increase or decrease the position by 1 (with equal probability). The walk stops when 3 or -3 is hit. The output should look like this:
position = 0
position = 1
position = 0
position = -1
position = -2
position = -1
position = -2
position = -3
max position = 1
(Intro to java help?)
Explanation / Answer
RandomWalkTest.java
import java.util.Random;
public class RandomWalkTest {
public static void main(String[] args) {
randomWalk();
}
public static void randomWalk() {
Random r = new Random();
int n = 0;
do {
int rand = r.nextInt(2);
if(rand==0) {
n++;
} else {
n--;
}
System.out.println("Position: "+n);
}while(n < 3 && n >-3);
}
}
Output:
Position: -1
Position: 0
Position: -1
Position: 0
Position: 1
Position: 2
Position: 3
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.