最优化的方法来更新Scala中的二维数组元素

时间:2013-08-04 12:08:53

标签: scala

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

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

2 个答案:

答案 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))
))