我有一个名为Grid的结构,它是10个单元格x 10个单元格, 我需要确定给定单元格的相邻单元格的位置。 < / p>
每个单元格的位置范围为(0,0)到(9,9)。职位是typealias Position = (row: Int, col: Int)
。 norm 将位置标准化,例如确保像(12,0)这样的东西被映射回10x10网格为(2,0)。
func norm(_ val: Int, to size: Int) -> Int {
return ((val % size) + size) % size
}
Grid的这个扩展应该确定给定像(6,3)这样的单元格的所有相邻单元格的位置。 我已经评论了我试图找出的部分。 我试图在x和y坐标上运行规范邻居们确定他们的实际位置。
extension Grid {
func neighbors(of cell: Cell) -> [Position] {
// return Grid.offsets.map{(norm($0, to: rows)), (norm($1, to: cols))}
}
}
在Grid结构中,所有8个可能的相邻位置都包含在偏移中。
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)
]
...
}
}
答案 0 :(得分:1)
因为您要映射偏移量,所以需要将它们添加到单元格的当前位置以获取其相邻单元格的绝对位置。您还要映射Position
元组的数组,因此地图闭包中只有一个参数将是Position
- 所以而不是$0
和$1
,您需要$0.row
和$0.col
。
return Grid.offsets.map { (norm($0.row + cell.position.row, to: rows), norm($0.col + cell.position.col, to: cols)) }
请注意,由于您的norm
功能,这将包装。例如,此函数会说(row: 3, col: 0)
处的单元格位于(row: 3, col: 9)
处的单元格旁边