Reputation: 1233
How do I get a random number between two numbers say 20 to 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)?
Thanks!
Upvotes: 46
Views: 73614
Reputation: 5627
I would recommend using Random.between(a, b)
Note that a
in inclusive, and b
is exclusive.
Refer to documentation here.
val r = new scala.util.Random
//to print 10 random numbers between 20 and 30 inclusive
(1 to 10).foreach(x =>
println(r.between(20, 30+1))
)
Output
28
26
29
30
22
29
28
22
20
24
Process finished with exit code 0
Upvotes: 2
Reputation: 824
Sure. Just do
// random number between 20 and 30 inclusive
val r = new scala.util.Random
20 + r.nextInt(11)
Upvotes: 28
Reputation: 7117
You can use java.util.concurrent.ThreadLocalRandom as an option. It's preferable in multithreaded environments.
val random: ThreadLocalRandom = ThreadLocalRandom.current()
val r = random.nextLong(20, 30 + 1) // returns value between 20 and 30 inclusively
Upvotes: 10
Reputation: 61716
Starting Scala 2.13
, scala.util.Random
provides:
def between(minInclusive: Int, maxExclusive: Int): Int
which used as follow, generates an Int
between 20 (included) and 30 (excluded):
import scala.util.Random
Random.between(20, 30) // in [20, 30[
Upvotes: 57
Reputation: 15307
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)
Upvotes: 58
Reputation: 20415
Also scaling math.random
value which ranges between 0
and 1
to the interval of interest, and converting the Double
in this case to Int
, e.g.
(math.random * (30-20) + 20).toInt
Upvotes: 8