How to generate a random number from 1 to 100 only once?

半世苍凉 提交于 2019-11-29 18:15:33

Fill an array with the numbers 1 to 100.

Randomly shuffle it (use Fisher-Yates shuffle).

Take each number starting from the first array index onwards...

Fill an Array '_randomNumbers' with the numbers 1-100. Each time you need a number use the following:

if (_randomNumbers.length>0) {
newRandomNumber = _randomNumbers.splice( Math.floor(Math.random(_randomNumbers.length)), 1 )[0];
}
Shakeeb Ayaz

check out this for more detail

 class NonRepeatedPRNG {
private final Random rnd = new Random();
private final Set<Integer> set = new HashSet<>();
public int nextInt() {
for (;;) {
  final int r = rnd.nextInt();
  if (set.add(r)) return r;
}
}
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!