简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM