1

For my specific purposes, I need to generate a whole number between 1 and 120 inclusive (which I can do no problem).

Once that number has been generated, I need to pull it from the pool so it can't be generated again.

Continue this process until all numbers are exhausted, at which point, the pool fills back up and we start over again.

How could I go about doing this?

p.campbell
  • 98,673
  • 67
  • 256
  • 322
Corey
  • 25
  • 5

3 Answers3

4

Generate the whole list of numbers from 1 to 120. Shuffle the list. Take the first element (and remove it)

List<Integer> list = new LinkedList<Integer>();
for (int i = 1; i <= 120; i++) {
    list.add(i)
}
Collections.shuffle(list);
...
int random = list.remove(0);
...
int otherRandom = list.remove(0);

Check for list.empty() in case you run out of numbers. If empty, create the list again and shuffle it.

aromero
  • 25,681
  • 6
  • 57
  • 79
0

The obvious way to do it is to fill a list with all numbers between 1 and 120, then when you need a random number, generate one between 1 and the list count, take the item from the list at that index, return it to the caller and then remove it from the list. Once the list is empty, refill and keep picking indices.

Blindy
  • 65,249
  • 10
  • 91
  • 131
0

I believe that all you need is to shuffle an array or a collection. You can refer to this question for example.

Community
  • 1
  • 1
kgiannakakis
  • 103,016
  • 27
  • 158
  • 194