find immediate neighbors (north, east, south, west) of any tile #n in a 9x9 grid in swift

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.swift
let row = n / 9
let col = n % 9
32 chars
3 lines

Then, we can find the indices of the immediate neighbors using simple arithmetic:

main.swift
let north = (row > 0) ? (n - 9) : nil   // check if not in top row
let east = (col < 8) ? (n + 1) : nil    // check if not in rightmost column
let south = (row < 8) ? (n + 9) : nil   // check if not in bottom row
let west = (col > 0) ? (n - 1) : nil    // check if not in leftmost column
288 chars
5 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.swift
let row = n / 9
let col = n % 9

let north = (row > 0) ? (n - 9) : nil
let east = (col < 8) ? (n + 1) : nil
let south = (row < 8) ? (n + 9) : nil
let west = (col > 0) ? (n - 1) : nil

print("Neighbors of tile #\(n): north=\(north ?? -1), east=\(east ?? -1), south=\(south ?? -1), west=\(west ?? -1)")
301 chars
10 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.swift
Neighbors of tile #40: north=31, east=41, south=49, west=39
60 chars
2 lines

related categories

gistlibby LogSnag