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

We can consider a square grid with a one-dimensional array, with sides of n length. Here's an example of how to calculate immediate neighbors:

main.swift
func getNeighbors(of n: Int, inGridWithSideLength sideLength: Int) -> [Int] {
    var neighbors = [Int]()
    
    // check north neighbor
    if n >= sideLength {
        neighbors.append(n - sideLength)
    }
    
    // check east neighbor
    if (n + 1) % sideLength != 0 {
        neighbors.append(n + 1)
    }
    
    // check south neighbor
    if n < (sideLength * sideLength) - sideLength {
        neighbors.append(n + sideLength)
    }
    
    // check west neighbor
    if n % sideLength != 0 {
        neighbors.append(n - 1)
    }
    
    return neighbors
}
575 chars
26 lines

Assuming n is the tile number we want to find the neighbors of, and sideLength is the length of a side of the square grid (i.e. the number of columns/rows).

  • The north neighbor is n - sideLength only if n is not in the top row.
  • The east neighbor is n + 1 only if n is not in the last column.
  • The south neighbor is n + sideLength only if n is not in the bottom row.
  • The west neighbor is n - 1 only if n is not in the first column.

The above function returns an array of tile numbers of immediate neighbors, so we can use it as follows:

main.swift
let sideLength = 4
let tileNumber = 5
let neighbors = getNeighbors(of: tileNumber, inGridWithSideLength: sideLength)
print(neighbors) // [1, 4, 6, 9]
150 chars
5 lines

This means that the tile number 5 has the neighbors 1 (to the north), 4 (to the west), 6 (to the east), and 9 (to the south).

related categories

gistlibby LogSnag