0

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.

limonik
  • 499
  • 1
  • 6
  • 28
  • 1
    Use something that doesn't allow duplicates, e.g. [HashSet](http://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html)? Or just add the generated numbers to a List, and check if the list already contains it? – almightyGOSU Jun 26 '15 at 11:55
  • What's your goal here? What would you like the program to do that your current code fails at? – Sam Estep Jun 26 '15 at 11:57

3 Answers3

2

Set doesn't allow duplicates

Set set = new HashSet();

while (set.size() < 20) {
    set.add(r.nextInt(100));
}
Uma Kanth
  • 5,659
  • 2
  • 20
  • 41
0

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.

jotadepicas
  • 2,389
  • 2
  • 26
  • 48
0

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.

Sagar
  • 125
  • 1
  • 15