Reputation: 499
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
Reputation: 135
You should follow below algorithmic steps to get solution for requirement:
Declare auxiliary container to store your ATN numbers, here Set is appropriate as Set do not allow duplicate entries.
Generate random number.
Check if this is presented in your auxiliary container?
Yes then go to step 2.
No then save to auxiliary storage.
Do your business logic.
Upvotes: 0
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
Reputation: 5629
Set doesn't allow duplicates
Set set = new HashSet();
while (set.size() < 20) {
set.add(r.nextInt(100));
}
Upvotes: 2