开发者

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开发者_Go百科 ways of doing this but I'm wondering what you all think.


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.


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


Generate a random number R in the entire domain (subtract the size of N from the max value) that you want to use. Then loop through all N less than R and for each add 1 to R. This will give a random number in the domain that is not in N.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜