javarandomrandom-seed

How can I generate multiple random numbers from the same seed in Java?


I'm trying to generate a randomized bingo board that is 5x5. My program generates 25 random numbers and assigns each one to a spot on the bingo board. I need to be able to have a user enter a custom seed which is used in the random number generation so that multiple people can be able to play with the same board (yes I know this is counterintuitive in bingo but I still need to be able to do it).

The current issue is that when using a set seed, the random number generator will generate the same number every time, filling the board with clones of a single number. How can I use a singular seed to generate the same board multiple times without all the random numbers being the same?

Disclamer: I've only been in computer science for 2 semesters so I'm a beginner! Go easy on me!

My random generator method looks something like this:

public void random(long seed)
    {
        Random rand = new Random(seed);
            randomInt = rand.nextInt(50);
    }

Solution

  • Create the Random once in the constructor, then use the same instance each time to generate the next number.

    For example:

    public class Board {
        private final Random rand;
        public Board(long seed) {
            this.rand = new Random(seed);
        }
        public void someMethod() {
            int randomInt = rand.nextInt(50);
            // do something with randomInt
        }
    }