Search code examples
javarandomintegerunique

Unique Random Integer Generator


I'm trying to make a random Integer generator that produces unique numbers.

Does anyone has any ideas how's that possible?


Solution

  • If you have a small-enough range of possible numbers, then this is very simple and useful:

    final List<Integer> sack = new ArrayList<>(RANGE);
    for (int i = 0; i < RANGE; i++) sack.add(i);
    Collections.shuffle(sack);
    

    Now just pull items out of sack in order.