How to execute a function k times?
I have a function that generates random numbers like this:
def genRandom(): Double = { //pass return something }
Now, how can I call the above function to generate a k-dimensional random vector? I thought how
(0 to k).foreach {
// FIXME Vec.append(getRandom())
}
But it doesn't work.
How do I call this function genRandom
k times and create a random vector from it?
source to share
Note that foreach
provides Unit
, not a set, from applying some of the argument (s) to a function. As mentioned above, use map
, for-yield
or fill
over a Vector
. On the latter, consider also tabulate
, which allows you to generate multi-dimensional vectors; in this context, however,
Vector.tabulate(k)(_ => genRandom())
In the case of two-dimensional (n times m) Vector
,
Vector.tabulate(n,m)((_,_) => genRandom())
source to share