logo CodeStepByStep logo

randomWalk

Language/Type: Java while parameters Random
Related Links:

Write a method named randomWalk that simulates a 1-dimensional "random walk" algorithm. A random walk is where an integer value is repeatedly increased or decreased by 1 randomly many times until it hits some threshold. Your method should accept the integer threshold as a parameter, then start an integer at 0 and adjust it by +1 or -1 repeatedly until its value reaches positive or negative threshold. For example, if the call of randomWalk(3); is made, your method would randomly walk until it hits 3 or -3. Each time the value is adjusted, it is printed in the format shown. When you have reached the threshold, report the number of steps that were taken from the starting point of 0, as well as the maximum position that was reached during the walk. (If the walk ever reaches positive threshold, that is the maximum position.)

The log below shows the output from an example call of randomWalk(3); . You should match the output format below exactly, though the numbers are randomly generated. Use a Random object and give an equal chance of moving by +1 and -1 on each step. If the threshold parameter passed to your method is not greater than 0, your method should produce no output.

Position = 0
Position = 1
Position = 0
Position = -1
Position = -2
Position = -1
Position = -2
Position = -3
Finished after 7 step(s)
Max position = 1

(Because this problem uses random numbers, it is hard for our system to perfectly verify your code. Make sure to match our output format exactly.)

Method: Write a Java method as described, not a complete program or class.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.