Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a list of random numbers?

Tags:

scala

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

like image 596
Michael Lorton Avatar asked Sep 26 '22 08:09

Michael Lorton


People also ask

How do I generate multiple random numbers in Excel?

To generate multiple random numbers in multiple cells, select the target cells, enter the RANDBETWEEN function, and press control + enter to enter the same formula in all cells at once.


2 Answers

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.

like image 100
Nicolas Avatar answered Oct 08 '22 19:10

Nicolas


How about:

import util.Random.nextInt
Stream.continually(nextInt(100)).take(10)
like image 37
Don Mackenzie Avatar answered Oct 08 '22 19:10

Don Mackenzie