Wednesday 26 July 2023

Controlling Randomness in Java: Exploring the Role of Seeds in java.util.Random

'java.util.Random' class is used to generate a stream of pseudorandom numbers. As per java documentation, if two instances of Random are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers.

So by specifying the same seed value when creating a Random object allows us to control the randomness and make sure that the sequence of random numbers generated remains the same across different executions of your program.

 

Find the below working application.

 


 

 

RandomExample.java

package com.sample.app;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class RandomExample {
	public static List<Integer> randomNumbers(int n, int randomSeed) {
		// Create a Random object with a seed value (randomSeed)
		Random random = new Random(randomSeed);
		
		List<Integer> resultList = new ArrayList<>();

		// Generate some random numbers using the first Random object
		for (int i = 0; i < n; i++) {
			resultList.add(random.nextInt(500));
		}
		return resultList;
	}

	public static void main(String[] args) {

		List<Integer> randomList1 = randomNumbers(10, 235711);
		List<Integer> randomList2 = randomNumbers(10, 235711);
		List<Integer> randomList3 = randomNumbers(10, 235711);
		
		System.out.println("randomList1 : " + randomList1);
		System.out.println("randomList2 : " + randomList2);
		System.out.println("randomList3 : " + randomList3);
	}
}

Output

randomList1 : [476, 110, 135, 430, 290, 479, 355, 380, 468, 189]
randomList2 : [476, 110, 135, 430, 290, 479, 355, 380, 468, 189]
randomList3 : [476, 110, 135, 430, 290, 479, 355, 380, 468, 189]

As you can see the output, randomList1 , randomList12 and randomList3 generate the same sequence of random numbers because they were created with the same seed (235711). Controlling the randomness ensure the same sequence of random numbers used in testing, debugging the application when you want to do with same set of random data on every execution.,

 

References

https://docs.oracle.com/javase/8/docs/api/java/util/Random.html

https://pytorch.org/docs/stable/notes/randomness.html

 



You may like

Interview Questions

How to get all the enum values in Java?

Extend the thread to check it’s running status

Implement retry handler for a task in Java

Design an utility class to capture application metrics summary in Java

Utility class to get primitive type from wrapper type and vice versa

FNV hash algorithm implementation in Java

No comments:

Post a Comment