prevent repetition of the numbers by not use of Collection Shuffle [Java]

88 views Asked by At

I used random function in my code however i dont know how could i prevent repetition.Also i read another questions about this subject but i dont want to use "Shuffle".

Thanks for all help and clues.

3

There are 3 answers

0
Uma Kanth On BEST ANSWER

Set doesn't allow duplicates

Set set = new HashSet();

while (set.size() < 20) {
    set.add(r.nextInt(100));
}
0
jotadepicas On

By definition, randomness includes de possibility of repetition, because every calculated random number is independent from the previous ones.

You should update your logic to save the generated numbers into a list for example, and check if the number is contained in such list. If it is, loop until it generates a new one.

You could also add a maximum loop count to avoid the program hanging forever.

0
Sagar On

You should follow below algorithmic steps to get solution for requirement:

  1. Declare auxiliary container to store your ATN numbers, here Set is appropriate as Set do not allow duplicate entries.

  2. Generate random number.

  3. Check if this is presented in your auxiliary container?

  4. Yes then go to step 2.

  5. No then save to auxiliary storage.

  6. Do your business logic.