How to generate a random number from 1 to 100 only

2020-02-16 05:54发布

问题:

I need to generate a random number from 1 to 100 in AS3 that will not be generated twice. So I need every number be generated until all the numbers are complete. How can I do that?

回答1:

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...



回答2:

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];
}


回答3:

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;
}
}
}