Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most optimized way to update elements of a 2d array in Scala

Tags:

scala

This piece of code updates all elements of a 2d array with some random value, is there any another simple and short code to solve this problem?

val terrainTypes = TerrainBlockType.values

(0 until width).foreach(i => {
    (0 until height).foreach(j => {
        val r = Random.nextInt(terrainTypes.length)
        terrainMap(i)(j) = terrainTypes(r)
    })
})
like image 520
Pooya Avatar asked Dec 07 '22 06:12

Pooya


2 Answers

Short code with new Array creation:

val terrainMap =
  Array.tabulate(width, height){ (_, _) =>
    terrainTypes(Random.nextInt(terrainTypes.length))
  }

If you need for loop optimization take a look at Scalaxy:

for {
  i <- 0 until width optimized;
  j <- 0 until height optimized
} {
  val r = Random.nextInt(terrainTypes.length)
  terrainMap(i)(j) = terrainTypes(r)
}

Scalaxy optimizes for-comprehensions using while loop.

like image 175
senia Avatar answered Dec 08 '22 19:12

senia


If you want to update an array which already exists:

terrainMap.foreach(_.transform(_ =>
  terrainTypes(Random.nextInt(terrainTypes.length))
))
like image 31
Jean-Philippe Pellet Avatar answered Dec 08 '22 20:12

Jean-Philippe Pellet