[英]Exclude number from SecureRandom random number generation
Let's say we have a random number generator using this:假设我们有一个使用这个的随机数生成器:
SecureRandom.random_number(10)
Which gives you a random number from 0 to 10.这会给你一个从 0 到 10 的随机数。
Would it be possible to exclude the number from it?是否可以从中排除数字? Let's say it would be 8.假设它将是8。
I was thinking about something about this:我在想这件事:
[SecureRandom.random_number(10)].grep_v(8)
But might be there is a more correct and optimized way?但是可能有更正确和优化的方法吗?
Ruby 2.7.2 Ruby 2.7.2
Rails 6.1.2导轨 6.1.2
Instead of generating a number up to 10, you could generate a number up to 9 and if the result is 8 or above, add 1:您可以生成最大为 9 的数字,而不是生成最多 10 的数字,如果结果为 8 或更大,则加 1:
number = SecureRandom.random_number(9)
number += 1 if number >= 8
Or you could generate a list of valid numbers and pick one of them randomly, eg via sample
:或者您可以生成一个有效数字列表并随机选择其中一个,例如通过sample
:
VALID_NUMBERS = [0, 1, 2, 3, 4, 5, 6, 7, 9]
number = VALID_NUMBERS.sample(random: SecureRandom)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.