生成随机数(不包括范围) [英] Generating random number excluding range
本文介绍了生成随机数(不包括范围)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在一个范围内生成一个随机数,同时排除某些范围.例如.范围为1-10,但不在2-4或7之间. 到目前为止,我使用过的解决方案:
How do you generate a random number within a range while excluding certain range(s). Eg. range 1-10 but not in 2-4 or 7. Solutions I've used so far:
- 生成随机测试,如果它 在不允许的范围内. 根据结果,要么输出 数字或重试.
- 允许地图 范围均匀.得到 在1到6之间随机,然后映射 后退(即6变成10).
- 创建 允许范围(1-1,5-6,8-10). 随机选择一个范围(可选 使用权重)和选择的数字 范围.
- Generate a random an test if it is within the dis-allowed range. Based on result either output the number or try again.
- Map allowed ranges to a uniform range. Get a random between 1 and 6 and then map back (ie. 6 becomes 10).
- Create allowed ranges (1-1,5-6,8-10). Randomly choose a range (optionally use weights) and a number in chosen range.
您的解决方案是什么?
推荐答案
(b)使用单个范围并映射到允许的值.
(a)速度较慢,运行时间不确定,因为您必须等待直到获得正确范围内的数字.如果您要跳过较大的范围,则会被软管淹没.
(a) Is slower and running time is non-deterministic because you have to wait until you get a number in the right range. If you were to skip a large range, you'd be hosed.
(c)比(b)更复杂;如果不需要,不要增加复杂性.
(c) Is more complex than (b); don't add complexity if it isn't required.
这篇关于生成随机数(不包括范围)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文