The most optimized way to update 2d array elements in Scala

This piece of code updates all the elements of a 2d array with some random value, is there 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) }) }) 
+4
source share
2 answers

If you want to update an existing array:

 terrainMap.foreach(_.transform(_ => terrainTypes(Random.nextInt(terrainTypes.length)) )) 
+5
source

Short code with new Array creation:

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

If you need to optimize the for loop, check out 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 a while loop.

+8
source

Source: https://habr.com/ru/post/1495183/


All Articles