2.7. Generating Random Numbers

Problem

You need to create random numbers, such as when testing an application, performing a simulation, and many other situations.

Solution

Create random numbers with the Scala scala.util.Random class. You can create random integers:

scala> val r = scala.util.Random
r: scala.util.Random = scala.util.Random@13eb41e5

scala> r.nextInt
res0: Int = −1323477914

You can limit the random numbers to a maximum value:

scala> r.nextInt(100)
res1: Int = 58

In this use, the Int returned is between 0 (inclusive) and the value you specify (exclusive), so specifying 100 returns an Int from 0 to 99.

You can also create random Float values:

// returns a value between 0.0 and 1.0
scala> r.nextFloat
res2: Float = 0.50317204

You can create random Double values:

// returns a value between 0.0 and 1.0
scala> r.nextDouble
res3: Double = 0.6946000981900997

You can set the seed value using an Int or Long when creating the Random object:

scala> val r = new scala.util.Random(100)
r: scala.util.Random = scala.util.Random@bbf4061

You can also set the seed value after a Random object has been created:

r.setSeed(1000L)

Discussion

The Random class handles all the usual use cases, including creating numbers, setting the maximum value of a random number range, and setting a seed value. You can also generate random characters:

// random characters
scala> r.nextPrintableChar
res0: Char = H

scala> r.nextPrintableChar
res1: Char = r

Scala makes it easy to create a random-length range of numbers, which is ...

Get Scala Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.