ulrich ulrich - 3 months ago 9
Scala Question

Generating values programmatically scala

Is it possible to recursively generate a series of values with a function in Scala?

Something like this:

def generateVal (nbrOfVal: Int) {
for (i <- 1 to nbrOfVal) {
val foo[i] = Seq.fill(6)(nextInt(100))}
}


So that it would be possible to use the val directly.

For instance generateVal(2) would give:

foo1: Seq[Int] = List(52, 83, 33, 85, 36, 39)
foo2: Seq[Int] = List(84, 47, 53, 66, 13, 72)


and then we could do:

foo1.zipAll(foo2, 0, 0).map { case (a, b) => a + b }
res: Seq[Int] = List(136, 130, 86, 151, 49, 111)

Answer

Here is a full example, println statements can be used for debugging (to see what's going on). They generally slow down the execution...

import scala.util.Random

object Randoms extends App {

  def generateVal(numOfLists: Int, numOfElements: Int): Seq[Seq[Int]] =
    for (i <- 1 to numOfLists) yield {
      Seq.fill(numOfElements)(Random.nextInt(100))
    }

  val (numOfLists, numOfElements) = (2, 5)
  val listOfLists = generateVal(numOfLists, numOfElements)

  // listOfLists foreach println // debug

  val startingList = Seq.fill(numOfElements)(0) // must have same # of elements, for zipping!
  val finalList = listOfLists.fold(startingList) { (s1, s2) =>
    //println(s"s1 = $s1") // debug
    //println(s"s2 = $s2") // debug
    (s1 zip s2) map { case (a, b) => a + b }
  }

  // println(finalList)
}
Comments