英文:
How can I generate multiple random numbers from the same seed in Java?
问题
我试图生成一个5x5的随机化Bingo板。我的程序生成25个随机数,并将每个数分配到Bingo板的一个位置。我需要让用户输入一个自定义的种子,用于随机数生成,以便多人可以使用相同的板进行游戏(是的,我知道这在Bingo中有些不合逻辑,但我仍然需要能够这样做)。
目前的问题是,当使用固定的种子时,随机数生成器每次都生成相同的数字,使整个板上充满相同的数字副本。如何使用相同的种子多次生成相同的板,而不使所有随机数都相同呢?
免责声明:我只学习计算机科学两个学期,所以我是初学者!请对我宽容点!
我的随机生成方法大致如下:
public void random(long seed)
{
Random rand = new Random(seed);
randomInt = rand.nextInt(50);
}
英文:
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);
}
答案1
得分: 2
在构造函数中创建Random
一次,然后每次使用相同的实例来生成下一个数字。
例如:
public class Board {
private final Random rand;
public Board(long seed) {
this.rand = new Random(seed);
}
public void someMethod() {
int randomInt = rand.nextInt(50);
// 使用 randomInt 进行一些操作
}
}
英文:
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
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论