我不喜欢我下面的 surroundingPositions
实现来获取特定位置周围的 x 和 y 坐标,因为在我看来,它对于简单的意图来说太长了,而且它有一个厄运结构金字塔。
struct Position: CustomStringConvertible {
let x, y: Int
var surroundingPositions: [Position] {
var surroundingPositions: [Position] = []
for x in (self.x - 1)...(self.x + 1) {
for y in (self.y - 1)...(self.y + 1) {
if !(x == self.x && y == self.y) {
surroundingPositions.append(Position(x: x, y: y))
}
}
}
return surroundingPositions
}
var description: String {
return "(\(x),\(y))"
}
}
用法:
let testPosition = Position(x: 1, y: 1)
print(testPosition.surroundingPositions)
// Output: [(0,0), (0,1), (0,2), (1,0), (1,2), (2,0), (2,1), (2,2)]
实现相同(正确)结果的最短方法是什么?我正在考虑像 map
、filter
、reduce
等函数,但到目前为止找不到合适的组合...
最佳答案
好吧,您总是可以对其进行硬编码。在这里,我对增量进行了硬编码,并为每个增量创建了一个新的 Position
:
var surroundingPositionsHardcoded: [Position] {
let deltas: [(Int, Int)] = [(-1, -1), (-1, 0), (-1, +1), (0, -1), (0, +1), (+1, -1), (+1, 0), (+1, +1)]
return deltas.map { Position(x: x+$0.0, y: y+$0.1) }
}
或者,您可以使用 map
计算增量。这还有一个额外的好处,就是可以增加周围的距离。
var surroundingPositionsComputed: [Position] {
let deltas = (-1...1).map { dx in (-1...1).map { dy in (dx, dy) } }
.joined()
.filter { $0.0 != 0 || $0.1 != 0 }
return deltas.map { Position(x: x+$0.0, y: y+$0.1) }
}
关于swift - 获取周围坐标的最短代码是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44180840/