One way of representing a 9x9 grid in Swift is by using an array of arrays. Each inner array will represent a row of the grid.
First, we need to find the row and column indices of the given tile number n
. Assuming the tiles are numbered from 0 to 80 (left to right, top to bottom), we can calculate:
main.swift32 chars3 lines
Then, we can find the indices of the immediate neighbors using simple arithmetic:
main.swift288 chars5 lines
If any of the neighbors are outside the grid (e.g. north
when n
is in the top row), their value will be set to nil
.
Putting it all together:
main.swift301 chars10 lines
This will output the indices of the immediate neighbors of the given tile number n
. Note that -1
is printed for neighbors that are outside the grid.
Example output for tile #40:
main.swift60 chars2 lines
gistlibby LogSnag