In this tutorial, we’ll see how we can generate a list of random numbers in Scala
2. Generate a List of Random Numbers in Scala
The first step we need to achieve is to generate a single random number in Scala.
2.1. Generate a Random Number in Scala
While there are a few possible approaches to do this, let’s focus on the most common:
scala> val rand = new scala.util.Random val rand: scala.util.Random = scala.util.Random@1f992a3a scala> rand.nextInt() val res0: Int = -1865253155 scala> rand.nextInt() val res1: Int = 2082034767 scala> rand.nextInt() val res2: Int = 917778542
2.2. Generate a List of Random Numbers
Now that we know how to generate a random number, let’s see how can we generate a list of random numbers.
A naive approach would be to just use a loop to generate the numbers we need. Let’s see how can we generate a list of five random numbers with a “loop” approach:
scala> import util.Random scala> (1 to 5).map(_ => Random.nextInt) val res12: IndexedSeq[Int] = Vector(-1928511932, -1575256831, -969308299, 662782782, 561362819)
And we achieved our goal. But there are more idiomatic approaches. Here’s one of them:
scala> import util.Random scala> Seq.fill(5)(Random.nextInt) val res8: Seq[Int] = List(1688342166, -670642581, -1132794330, -1897917663, 1451652053)
Here we use the Seq.fill() method to produce a Seq of five elements using the generator function, which in our case is the random generator.
Yet another approach is to use Streams (also called LazyList in newer Scala versions):
scala> import util.Random scala> val stream = LazyList.continually(Random.nextInt()) val stream: LazyList[Int] = LazyList(<not computed>) scala> stream.take(5) val res1: LazyList[Int] = LazyList(<not computed>) scala> stream.take(5).toList val res2: List[Int] = List(-118669320, -1725151991, 218597541, 1650982106, 1147159538)
In the above example, we create an infinite stream of random numbers. We can then take as many elements as we want (five in our example). We then need to actually evaluate the stream, so we convert it into a common List to get the random numbers.
In this article, we saw how to generate a list of random numbers in Scala using different approaches.