How to generate a list of random numbers?

Scala

Scala Problem Overview


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.

EDIT

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..."

Scala Solutions


Solution 1 - Scala

You can either use Don's solution or:

Seq.fill(n)(Random.nextInt)

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

Solution 2 - Scala

How about:

import util.Random.nextInt
Stream.continually(nextInt(100)).take(10)

Solution 3 - Scala

regarding your EDIT,

nextInt can take an Int argument as an upper bound for the random number, so 1 to 20 map r.nextInt is the same as 1 to 20 map (i => r.nextInt(i)), rather than a more useful compilation error.

1 to 20 map (_ => r.nextInt(100)) does what you intended. But it's better to use Seq.fill since that more accurately represents what you're doing.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMichael LortonView Question on Stackoverflow
Solution 1 - ScalaNicolasView Answer on Stackoverflow
Solution 2 - ScalaDon MackenzieView Answer on Stackoverflow
Solution 3 - ScalaLuigi PlingeView Answer on Stackoverflow