0

Hi in my Android application I need to generate all numbers(not together but when I call the function say generateAnyRandom()) in a certain range.

For example, say my range is 1 to 1000 and when I call generateAnyRandom() it should give a random number within the range. In this way, if again I call the function it should give me another random number which must be different from the existing one. And more importantly, I will call the function maximum of 1000 times as the range is 1 to 1000 and it should give me always a number that was not generated yet. That means I want to generate all the numbers from 1 to 1000 not in one shot but only when I call it.

Please help. It is a critical question for me?

Bhaskar Jyoti Dutta
  • 1,740
  • 2
  • 15
  • 30

1 Answers1

1

This is a known problem.

  1. Put the numbers 1..1000 into some container; an array, list, or whatever.
  2. Shuffle the contents of the container into random order.
  3. Retrieve the numbers from the shuffled container in order.

As you correctly point out, this will only work 1000 times before the container is exhausted. You should pick a type of container that allows you to easily perform a random shuffle. Check the various built-in functions for the different container types.

rossum
  • 15,344
  • 1
  • 24
  • 38
  • Thanks for pointing it out. I am now trying to do that but I am thinking about its speed i.e efficiency. – Bhaskar Jyoti Dutta May 04 '21 at 17:41
  • @BhaskarJyotiDutta if you know you're consuming more than half the items then this algorithm wins on speed and simplicity. if you were consuming significantly less items (i.e. < sqrt(n)) then it's certainly worth doing something else (e.g. rejection sampling). the middle ground it's less clear… note that most languages provide an O(n) shuffle – Sam Mason May 04 '21 at 21:42
  • 1
    Do not prematurely optimize. Code the problem the simplest way, and see if that is fast enough. If, and only if, that way is too slow then you can try to speed up the algorithm. – rossum May 04 '21 at 22:25