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)
})
})
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.
If you want to update an array which already exists:
terrainMap.foreach(_.transform(_ =>
terrainTypes(Random.nextInt(terrainTypes.length))
))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With