4

这段代码用一些随机值更新了二维数组的所有元素,还有其他简单而简短的代码来解决这个问题吗?

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

2 回答 2

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)
}

Scalaxyfor-comprehensions使用 while 循环进行优化。

于 2013-08-04T12:23:24.000 回答
7

如果要更新已经存在的数组:

terrainMap.foreach(_.transform(_ =>
  terrainTypes(Random.nextInt(terrainTypes.length))
))
于 2013-08-04T12:25:35.117 回答