SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Program Logic And Indefinite Loops
Exercise:
Exercises
Question:8 | ISBN:9780136091813 | Edition: 2

Question

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

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

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

 

0 0

Discussions

Post the discussion to improve the above solution.