What is the shortest code to get the coordinates?

I don't like my next implementation of surroundingPositions to get the x and y coordinates associated with a particular position, because, in my opinion, it is too long for simple intention and has a pyramid of fate 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))" } } 

Using:

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

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

+5
source share
2 answers

Well, you can always hardcode it. Here I hardcoded the delta 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) } } 

Or you can calculate the delta using map . This has the added benefit that you can 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) } } 
+4
source

Since you are only looking for neighboring positions and apparently do not have restrictions on x or y , you can save an array of translations (x, y) , each of which maps this Position one of its 8 neighboring ones.

 struct Position: CustomStringConvertible { let x, y: Int // order of resulting neighbouring positions, given a position P // (1) (2) (3) // (4) (P) (5) // (6) (7) (8) private static let surroundingPositionsTranslations: [(x: Int, y: Int)] = [ (-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, -1), (0, -1), (1, -1)] var surroundingPositions: [Position] { return Position.surroundingPositionsTranslations .map { Position(x: x + $0.x, y: y + $0.y) } } var description: String { return "(\(x),\(y))" } } // Note that I've changed the order wrt OP:s original code // (modify the transfotmation above to modify the order) let testPosition = Position(x: 1, y: 1) print(testPosition.surroundingPositions) // Output: [(0,0), (1,0), (2,0), (0,1), (2,1), (0,0), (1,0), (2,0)] 
+1
source

Source: https://habr.com/ru/post/1268232/


All Articles