任务:对于二维数组中的给定位置,生成位于半径内的周围位置列表。
例如:
input: (1, 1)
radius: 1
output: ( (0, 0), (1, 0), (2, 0),
(0, 1), (2, 1),
(0, 2), (1, 2), (2, 2) ).
我写了类似的东西
def getPositions(x:Int, y:Int, r:Int) = {
for(radius <- 1 to r) yield {
List(
for (dx <- -radius to radius) yield Pair(x + dx, y - radius),
for (dx <- -radius to radius) yield Pair(x + dx, y + radius),
for (dy <- -radius to radius) yield Pair(x + radius, y + dy),
for (dy <- -radius to radius) yield Pair(x - radius, y + dy)
)
}
}
在此代码中,getPositions 返回的不是点序列,而是点序列的 Tuple4 序列。如何“连接”代码中列出的 4 个生成器?或者我的任务有更简洁的解决方案吗?(我对 scala 很陌生)。
PS 这实际上是为我的星际争霸机器人准备的。