Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optimal algorithm for generating a random number R not in a set of numbers N

I am curious to know what the best way to generate a random integer R that is not in a provided set of integers (R∉N). I can think of several ways of doing this but I'm wondering what you all think.

like image 557
Alan Avatar asked Jul 29 '10 19:07

Alan


2 Answers

Let N be the size of the overall set, and let K be the size of the excluded set.

I depends on the size of the set you are sampling from. If the excluded set is much smaller than the overall range, just choose a random number, and if it is in the excluded set, choose again. If we keep the excluded set in a hash table each try can be done in O(1) time.

If the excluded set is large, choose a random number R in a set of size (N - K) and output the choice as the member of the non excluded elements. If we store just the holes in a hash table keyed with the value of the random number we can generate this in one sample in time O(1).

The cutoff point will depend on the size of (N - K)/N, but I suspect that unless this is greater than .5 or so, or you sets are very small, just sampling until you get a hit will be faster in practice.

like image 51
deinst Avatar answered Sep 21 '22 10:09

deinst


Given your limited description? Find the maximum value of the elements in N. Generate only random numbers greater than that.

like image 26
Nick Johnson Avatar answered Sep 20 '22 10:09

Nick Johnson