Sam Joos
Sam Joos

Reputation: 450

Java random without repetition

How can I implement an integer random, that can generate each number just one time but without repetition. I use this code in Android.

int random = Random.nextInt((max+1 - min) + min;

Problem: between max and min there is repeated numbers and also some numbers, they don't exist.

Upvotes: 0

Views: 186

Answers (2)

Martin Frank
Martin Frank

Reputation: 3474

instead of having a list (as mentioned from Derek Fung) with all possible values you

  • can store created values in an list
  • check if any new created value is in that list and then
    • add it to the list
    • or create a new value until you found one that is not in the list

Upvotes: 0

Derek Fung
Derek Fung

Reputation: 8211

You need a shuffle algorithm

https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle

create an array/list of the possible number, shuffle it, and then get the number once at a time

Upvotes: 3

Related Questions