生成不在一组数字 N 中的随机数 R 的最佳算法

发布于 2024-09-11 15:57:47 字数 82 浏览 1 评论 0原文

我很想知道生成随机整数 R 的最佳方法是什么,该随机整数 R 不在提供的整数集中 (R∉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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

别想她 2024-09-18 15:57:47

令 N 为整体集合的大小,令 K 为排除集合的大小。

I 取决于您从中采样的集合的大小。如果排除集远小于总体范围,则选择一个随机数,如果在排除集中,则重新选择。如果我们将排除集保留在哈希表中,则每次尝试都可以在 O(1) 时间内完成。

如果排除的集合很大,则在大小为 (N - K) 的集合中选择一个随机数 R,并将该选择输出为非排除元素的成员。如果我们仅将空洞存储在以随机数值作为键控的哈希表中,我们可以在一个样本中以 O(1) 的时间生成该值。

截止点将取决于 (N - K)/N 的大小,但我怀疑除非它大于 0.5 左右,或者您的集合非常小,否则在实践中仅进行采样直到命中会更快。

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.

你与昨日 2024-09-18 15:57:47

鉴于您的描述有限?找到 N 中元素的最大值。仅生成大于该值的随机数。

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

只想待在家 2024-09-18 15:57:47

在整个域中生成您要使用的随机数 R(从最大值中减去 N 的大小)。然后循环遍历所有小于 R 的 N,并对每个 R 加 1。这将在域中给出一个不在 N 中的随机数。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文