获取周围坐标的最短代码是什么? [英] What is the shortest code to get surrounding coordinates?

查看:21
本文介绍了获取周围坐标的最短代码是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不喜欢我对 surroundingPositions 的以下实现来获取围绕特定位置的 x 和 y 坐标,因为在我看来这对于简单的意图来说太长了,而且它有一个末日金字塔结构.

I don't like my following implementation of surroundingPositions to get the x- and y-Coordinates surrounding a specific position, because in my opinion it is too long for the simple intent and it has a pyramid of doom structure.

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

以相同(正确)结果实现此目的的最短方法是什么?我正在考虑像 mapfilterreduce 等函数,但到目前为止找不到正确的组合......

What is the shortest way to implement this with the same (correct) result? I'm thinking of functions like map, filter, reduce, etc., but can't find the right combination so far ...

推荐答案

好吧,您可以随时对其进行硬编码.在这里,我对增量进行了硬编码,并为每个增量创建了一个新的 Position:

Well, you could always hardcode it. Here, I hardcoded the deltas and create a new Position for each delta:

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 计算增量.这有一个额外的好处,你可以增加周围的距离.

Or, you could compute the deltas using map. This has the added benefit that you could increase the surrounding distance.

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

这篇关于获取周围坐标的最短代码是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆