ducin
ducin

Reputation: 26477

How to generate a sequence of random integers less than a number in Scala?

The task is to write a function that generates given number of integers that are not bigger than another given number. The code I've got now looks like that:

scala>   def lotto(count: Int, max: Int): Seq[Int] = {
     |     var result = Seq[Int]();
     |     var x: Int = 0;
     |     for(x <- 1 to count){
     |       result = scala.util.Random.nextInt(max) :+ result
     |     }
     |   }
<console>:13: error: value :+ is not a member of Int
             result = scala.util.Random.nextInt(max) :+ result
                                                     ^
<console>:12: error: type mismatch;
 found   : Unit
 required: Seq[Int]
           for(x <- 1 to count){
                 ^

It doesn't compile as you can see. Can someone please explain what's wrong here?

Upvotes: 2

Views: 1392

Answers (2)

Brian
Brian

Reputation: 20285

A couple of things as the compiler states.

:+ should be applied to result. :+ is method on Seq. Calling it the way you did tries to call it on Int which does not exist as the error says. Short story is to swap the order as shown below.

Scala returns the last value in a method. So, add result to the end as a return value.

def lotto(count: Int, max: Int): Seq[Int] = {
  var result = Seq[Int]();
  var x: Int = 0;
  for(x <- 1 to count){
    result = result :+ scala.util.Random.nextInt(max) 
  }
  result
}

Run it:

scala> lotto(10, 100)
res0: Seq[Int] = List(41, 75, 80, 80, 33, 44, 3, 24, 20, 28)

A more concise version of a mutable for comprehension would be to use fill

Seq.fill(count)((scala.math.random * max).toInt)

Or even:

Seq.fill(count)(util.Random.nextInt(max))

Upvotes: 6

Jesper
Jesper

Reputation: 206916

A more idiomatic way to write this is the following:

def lotto(count: Int, max: Int): Seq[Int] =
  for (x <- 1 to count) yield scala.util.Random.nextInt(max)

When you program in a functional programming style, avoid mutable data (var).

Upvotes: 3

Related Questions