Get a random number between two numbers in Scala

How to get a random number between two numbers, for example, from 20 to 30?

I tried:

val r = new scala.util.Random r.nextInt(30) 

This allows you to use only the upper bound value, but the values ​​always start with 0. Is there a way to set the lower bound value (up to 20 in the example)?

Thanks!

+12
source share
5 answers

You can use below. Both the beginning and the end will be included.

 val start = 20 val end = 30 val rnd = new scala.util.Random start + rnd.nextInt( (end - start) + 1 ) 

A case of you

 val r = new scala.util.Random val r1 = 20 + r.nextInt(( 30 - 20) + 1) 
+24
source

Sure. Just do

 20 + r. nextInt(10) 
+14
source

Also scaling math.random value that ranges between 0 and 1 to the interval of interest and converts Double in this case to Int , for example

 (math.random * (30-20) + 20).toInt 
+2
source

Running Scala 2.13 , scala.util.Random provides:

def between(minInclusive: Int, maxExclusive: Int): Int

which is used as follows generates an Int between 20 (included) and 30 (excluded):

 import scala.util.Random Random.between(20, 30) // in [20, 30[ 
0
source

You can use java.util.concurrent.ThreadLocalRandom as an option. This is preferred in multi-threaded environments.

 val random: ThreadLocalRandom = ThreadLocalRandom.current() val r = random.nextLong(20, 30 + 1) // returns value between 20 and 30 inclusively 
0
source

All Articles