3

I know about the JAVA Random class and its use. But I want to generate a random number which should not be repeated until all the numbers in the range are generated at least once. Can anybody provide me some reference..?

While using the Random class, the problem I face is that some numbers get repeated 2 or 3 times while some are not generated at all.. My application may fail in this scenario as I have another thread processing some requests based on the numbers getting generated....and the moment there is a delay and next unique digit is not available, it stops without processing the non - generated numbers...

ASingh
  • 475
  • 1
  • 13
  • 24
  • 1
    if your range is relatively small and you (optionally) want to support "reuse" of generated values once you're done with them, go with ben75's answer. otherwise Peter Lawrey's answer is the way to go. – Oren Jan 13 '13 at 11:17
  • possible duplicate of http://stackoverflow.com/questions/4040001/creating-random-numbers-with-no-duplicates – Harshdeep Jan 13 '13 at 11:17

3 Answers3

13

You can generate all the values in range and shuffle them. Collections.shuffle() Once you have uses every value, repeat.

Imagine you have decks of cards, You take one deck which has a every card once, you shuffle it and you will know what while each card will come in a random order, only once. When one deck has finished you take all the cards again and reshuffle (or a new deck and shuffle that)

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
3
  • Create a List with all the possible random numbers in the range.
  • Instead of using a random number as result, use a random integer to pick an index in the list
  • remove it from the list and return it.

Take care to adjust the range of random integer to the current list size (it will decrease by one each time you get a new number)

ben75
  • 29,217
  • 10
  • 88
  • 134
  • 1
    shuffling is better, as it is done only once in O(N) and then allows N O(1) accesses (which is better than O(N^2) if you extract N random elements one-by-one from a list, either linked [due to access-time] or array-backed [due to extraction time]) – tucuxi Jan 13 '13 at 11:40
1

you can keep a list with you of all the numbers that are already picked out and check if the new random number is in that list or not Here is an example of someone who asked the same question

Community
  • 1
  • 1
LaMa
  • 71
  • 5