Scala – How to generate a list of random numbers


This might be the least important Scala question ever, but it's bothering me. How would I generate a list of n random number. What I have so far:

def n_rands(n : Int) = {
 val r = new scala.util.Random
 1 to n map { _ => r.nextInt(100) } 

Which works, but doesn't look very Scalarific to me. I'm open to suggestions.


Not because it's relevant so much as it's amusing and obvious in retrospect, the following looks like it works:

1 to 20 map r.nextInt

But the index of each entry in the returned list is also the upper bound of that last. The first number must be less than 1, the second less than 2, and so on. I ran it three or four times and noticed "Hmmm, the result always starts with 0…"

Best Solution

You can either use Don's solution or:


Note that you don't need to create a new Random object, you can use the default companion object Random, as stated above.

Related Question