获取周围坐标的最短代码是什么?

Ben*_*ess 5 swift swift3

我不喜欢我的以下实现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))"
    }

}
Run Code Online (Sandbox Code Playgroud)

用法:

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)]
Run Code Online (Sandbox Code Playgroud)

使用相同(正确)结果实现此方法的最短方法是什么?我想的一样的功能map,filter,reduce等,但无法找到正确的组合至今...

thm*_*thm 4

好吧,你总是可以对它进行硬编码。在这里,我对增量进行了硬编码,并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) }
}
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用 计算增量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) }
}
Run Code Online (Sandbox Code Playgroud)