Java Random Walk Program

Java Random Walk Program | The random walk program performs a random one-dimensional (1D) walk. It reports each position reached and the maximum position reached during the walk.

The walk usually starts from 0, from each there should be a decrease or increase by a single position that is with equal probability. The walk stops when it reaches 3 or -3.

Java Random Walk Program

import java.util.Random;

public class Main {

   public static void main(String[] args) {

      int pos = 0;
      int max = 0;
      Random rand = new Random();
      int step;

      while (pos < 3 && pos > -3) {
         System.out.println("The current position is: " 
                           + pos);
         boolean bool = rand.nextBoolean();
         if (bool == false)
            step = 1;
         else
            step = -1;
         pos += step;
         max = Math.max(pos, max);
      }

      System.out.println("Position: " + pos);
      System.out.println("The maximum position is: " + max);

   }
}

Output:-

The current position is: 0
The current position is: 1
The current position is: 0
The current position is: -1
The current position is: -2
The current position is: -1
The current position is: 0
The current position is: 1
The current position is: 2
Position: 3
The maximum position is: 3

The current position is: 0
The current position is: -1
The current position is: -2
Position: -3
The maximum position is: 0

The current position is: 0
The current position is: 1
The current position is: 2
Position: 3
The maximum position is: 3

The current position is: 0
The current position is: -1
The current position is: -2
The current position is: -1
The current position is: 0
The current position is: -1
The current position is: 0
The current position is: 1
The current position is: 2
Position: 3
The maximum position is: 3

In the Java random walk program, we have imported the Java random class, this random class is used to generate pseudo-random numbers in Java.

In the main method, we have initialized the position and maximum value to 0 and instantiated the Java Random class by using the new keyword and then declare the integer variable step.

In the while loop, we check whether the position is lesser than 3 and greater than -3, then print the current position by using random. Go to the next position if the boolean is false then the step will be 1 or else the step will be -1. Then add the position to the step by using Math.max() to check the maximum value of the position and step. Repeat this step until the condition becomes false.

At last, we have printed the value of the final position & the maximum position reached in the program.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *