-4

I wanna create a random integer without duplicates when the max list is one length from my list.

I use this code but I have duplicates. What I should change?

Random rand = new Random();
n = rand.nextInt(QuestionLibrary.mChoices.length) + 1;
Cœur
  • 37,241
  • 25
  • 195
  • 267

1 Answers1

0

The solution outlined below is more efficient than checking that each random number hasn't been picked already.

The idea is that you populate a list with all possible numbers in your random range. Then, you shuffle the list. You get each new random number by subsequently popping items from the front of the shuffled list.

Generating Unique Random Numbers in Java

Stuckzilla
  • 587
  • 1
  • 3
  • 12
  • how i can use this to my project? – MariosGR Aug 07 '17 at 15:36
  • Add all possible random numbers to a new list. In your case the length of mChoices. Then, shuffle the order of the list using an existing java method. Now you can iterate through the list and each number you pull at the current index will be a unique random number in your range. – Stuckzilla Aug 07 '17 at 15:39
  • this int change my photo and questions and anwsers in my game.. so when i + photos i should +and this list? There is some easier way? – MariosGR Aug 07 '17 at 15:42