limonik
limonik

Reputation: 499

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

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.

Upvotes: 0

Views: 87

Answers (3)

Sagar
Sagar

Reputation: 135

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.

Upvotes: 0

jotadepicas
jotadepicas

Reputation: 2493

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.

Upvotes: 0

Uma Kanth
Uma Kanth

Reputation: 5629

Set doesn't allow duplicates

Set set = new HashSet();

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

Upvotes: 2

Related Questions