Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get random number between two numbers in Scala

Tags:

random

scala

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!

like image 657
vijay Avatar asked Sep 09 '16 01:09

vijay


People also ask

How to generate a random number in range in Scala?

To generate the Random numbers over Scala we use the Random function with the Scala. util. Random class. The Random number generated can be anything be it Integer, Float, Double, char.


2 Answers

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) 
like image 185
abaghel Avatar answered Oct 01 '22 11:10

abaghel


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[ 
like image 20
Xavier Guihot Avatar answered Oct 01 '22 11:10

Xavier Guihot