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?

+3


source to share


2 answers


Possible ways:

Vector.fill(k)(getRandom())

      

or



(0 until k).map( _ => getRandom())

      

or



 for ( i <- 0 until k ) yield getRandom()

      

+7


source


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())

      

+3


source







All Articles