3. Write a method randomWalk that performs a random one-dimensional walk, report
ID: 3566971 • Letter: 3
Question
3. 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: (3-credit) position = 0 position = 1 position = 0 position = -1 position = -2 position = -1 position = -2 position = -3 max position = 1Explanation / Answer
public void randomWalk()
{
int step=0,max=0;
System.out.println("Current Position= "+step);
while(!(step==3 || step==-3))
{
step+=Math.pow(-1,Math.round(Math.random()*10)); //(-1)^(even or odd)
if(max<step)max=step;
System.out.println("Current Position= "+step);
}
System.out.println("Maximum Position= "+max);
}