这段代码用一些随机值更新了二维数组的所有元素,还有另外一个简单的短代码来解决这个问题吗?
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)
})
})
答案 0 :(得分:8)
新Array
创建的简短代码:
val terrainMap =
Array.tabulate(width, height){ (_, _) =>
terrainTypes(Random.nextInt(terrainTypes.length))
}
如果您需要for
循环优化,请查看Scalaxy
:
for {
i <- 0 until width optimized;
j <- 0 until height optimized
} {
val r = Random.nextInt(terrainTypes.length)
terrainMap(i)(j) = terrainTypes(r)
}
Scalaxy
使用while循环优化for-comprehensions
。
答案 1 :(得分:6)
如果要更新已存在的数组:
terrainMap.foreach(_.transform(_ =>
terrainTypes(Random.nextInt(terrainTypes.length))
))