What's the recommended way of creating a pre-populated two-dimensional array in Scala? I've got the following code:
在Scala中创建预先填充的二维数组的推荐方法是什么?我有以下代码:
val map = for {
x <- (1 to size).toList
} yield for {
y <- (1 to size).toList
} yield (x, y)
How do I make an array instead of list? Replacing .toList with .toArray doesn't compile. And is there a more concise or readable way of doing this than the nested for expressions?
如何制作数组而不是列表?用.toArray替换.toList不会编译。还有比嵌套表达式更简洁或可读的方法吗?
2 个解决方案
#1
9
On Scala 2.7, use Array.range
:
在Scala 2.7上,使用Array.range:
for {
x <- Array.range(1, 3)
} yield for {
y <- Array.range(1, 3)
} yield (x, y)
On Scala 2.8, use Array.tabulate
:
在Scala 2.8上,使用Array.tabulate:
Array.tabulate(3,3)((x, y) => (x, y))
#2
2
Among other ways, you can use use Array.range
and map
:
除了其他方法,您可以使用使用Array.range和map:
scala> Array.range(0,3).map(i => Array.range(0,3).map(j => (i,j)))
res0: Array[Array[(Int, Int)]] = Array(Array((0,0), (0,1), (0,2)), Array((1,0), (1,1), (1,2)), Array((2,0), (2,1), (2,2)))
Or you can use Array.fromFunction
:
或者您可以使用Array.fromFunction:
scala> Array.fromFunction((i,j) => (i,j))(3,3)
res1: Array[Array[(Int, Int)]] = Array(Array((0,0), (0,1), (0,2)), Array((1,0), (1,1), (1,2)), Array((2,0), (2,1), (2,2)))
Scala 2.8 gives you even more options--look through the Array
object. (Actually, that's good advice for 2.7, also....)
Scala 2.8为您提供了更多选项 - 查看Array对象。 (实际上,这对2.7的好建议也是......)
#1
9
On Scala 2.7, use Array.range
:
在Scala 2.7上,使用Array.range:
for {
x <- Array.range(1, 3)
} yield for {
y <- Array.range(1, 3)
} yield (x, y)
On Scala 2.8, use Array.tabulate
:
在Scala 2.8上,使用Array.tabulate:
Array.tabulate(3,3)((x, y) => (x, y))
#2
2
Among other ways, you can use use Array.range
and map
:
除了其他方法,您可以使用使用Array.range和map:
scala> Array.range(0,3).map(i => Array.range(0,3).map(j => (i,j)))
res0: Array[Array[(Int, Int)]] = Array(Array((0,0), (0,1), (0,2)), Array((1,0), (1,1), (1,2)), Array((2,0), (2,1), (2,2)))
Or you can use Array.fromFunction
:
或者您可以使用Array.fromFunction:
scala> Array.fromFunction((i,j) => (i,j))(3,3)
res1: Array[Array[(Int, Int)]] = Array(Array((0,0), (0,1), (0,2)), Array((1,0), (1,1), (1,2)), Array((2,0), (2,1), (2,2)))
Scala 2.8 gives you even more options--look through the Array
object. (Actually, that's good advice for 2.7, also....)
Scala 2.8为您提供了更多选项 - 查看Array对象。 (实际上,这对2.7的好建议也是......)