I have a struct called Grid that is 10 cells x 10 cells, and I need to determine the position of a given cell's neighboring cells.
Every cell has a position ranging from (0,0) to (9,9). Position is typealias Position = (row: Int, col: Int)
. norm normalizes positions like makes sure that something like (12,0) gets mapped back to the 10x10 grid as (2,0).
func norm(_ val: Int, to size: Int) -> Int {
return ((val % size) + size) % size
}
This extension to Grid is supposed to determine the position of all neighboring cells given a cell like (6,3). I've commented out the part that I'm trying to figure out. I'm trying to run norm on the x and y coordinates of the neighbors to determine their actual position.
extension Grid {
func neighbors(of cell: Cell) -> [Position] {
// return Grid.offsets.map{(norm($0, to: rows)), (norm($1, to: cols))}
}
}
Within the Grid struct all 8 possible neighboring positions are contained within offsets.
struct Grid {
static let offsets: [Position] = [
(row: -1, col: 1), (row: 0, col: 1), (row: 1, col: 1),
(row: -1, col: 0), (row: 1, col: 0),
(row: -1, col: -1), (row: 0, col: -1), (row: 1, col: -1)
]
...
}
}