scala 在Scala中获取两个数字之间的随机数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39402567/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get random number between two numbers in Scala
提问by vijay
How do I get a random number between two numbers say 20 to 30?
如何获得两个数字之间的随机数,比如 20 到 30?
I tried:
我试过:
val r = new scala.util.Random
r.nextInt(30)
This allows only upper bound value, but values always starts with 0. Is there a way to set lower bound value (to 20 in the example)?
这仅允许上限值,但值始终以 0 开头。有没有办法设置下限值(在示例中为 20)?
Thanks!
谢谢!
回答by abaghel
You can use below. Both start and end will be inclusive.
您可以在下面使用。开始和结束都将包含在内。
val start = 20
val end = 30
val rnd = new scala.util.Random
start + rnd.nextInt( (end - start) + 1 )
In your case
在你的情况下
val r = new scala.util.Random
val r1 = 20 + r.nextInt(( 30 - 20) + 1)
回答by egprentice
Sure. Just do
当然。做就是了
20 + r. nextInt(10)
回答by Xavier Guihot
Starting Scala 2.13, scala.util.Randomprovides:
开始Scala 2.13,scala.util.Random提供:
def between(minInclusive: Int, maxExclusive: Int): Int
def between(minInclusive: Int, maxExclusive: Int): Int
which used as follow, generates an Intbetween 20 (included) and 30 (excluded):
其用法如下,生成Int介于 20(包括)和 30(不包括)之间的值:
import scala.util.Random
Random.between(20, 30) // in [20, 30[
回答by J-Alex
You can use java.util.concurrent.ThreadLocalRandomas an option. It's preferable in multithreaded environments.
您可以使用java.util.concurrent.ThreadLocalRandom作为选项。在多线程环境中更可取。
val random: ThreadLocalRandom = ThreadLocalRandom.current()
val r = random.nextLong(20, 30 + 1) // returns value between 20 and 30 inclusively
回答by elm
Also scaling math.randomvalue which ranges between 0and 1to the interval of interest, and converting the Doublein this case to Int, e.g.
也缩放math.random值之间的范围内0和1所关心的时间间隔,并转换Double在这种情况下Int,例如
(math.random * (30-20) + 20).toInt

