[英]Generate a random number with 7 digits
How can I produce a random number in a range from 1 million to 10 million?我怎样才能产生一个范围从 100 万到 1000 万的随机数?
rand(10)
works, I tried rand(1..10)
and that didn't work. rand(10)
有效,我试过rand(1..10)
但没有奏效。
取您的基数 1,000,000 并添加一个从 0 到您的最大值的随机数 - 起始数:
1_000_000 + Random.rand(10_000_000 - 1_000_000) #=> 3084592
这是一个实例方法:
puts Random.new.rand(1_000_000..10_000_000-1)
我发现这更具可读性:
7.times.map { rand(1..9) }.join.to_i
或者,如果性能不是问题并且您不想计算零:
(0...7).map { |i| rand((i == 0 ? 1 : 0)..9) }.join.to_i
This will generate a random number between 1,000,000 and 9,999,999.这将生成一个介于 1,000,000 和 9,999,999 之间的随机数。
rand(10_000_000-1_000_000)+1_000_000
This works in 1.8.7 without any gems(backports, etc).这适用于 1.8.7,没有任何 gems(backports 等)。
You can do this by following simple way. 您可以通过以下简单方式完成此操作。
rand(10 ** 6...10 ** 7 - 1) # range between 1000000 to 9999999 )
>> 1729679
rand(10 ** 6...10 ** 7 - 1)
>> 9789151
rand(10 ** 6...10 ** 7 - 1)
>> 8989718
Hope this will help you. 希望这会帮助你。
Another option with ruby 1.8.7 compatibility:与 ruby 1.8.7 兼容的另一个选项:
rand(9999999999).to_s.center(10, rand(9).to_s).to_i rand(9999999999).to_s.center(10, rand(9).to_s).to_i
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.