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

You can represent the axa grid as a two-dimensional array, and then use the indices method of the array to get the row and column of the current tile. Once you have the row and column, you can find the immediate neighbors by adjusting the row and column values accordingly. Here's an example function that takes a grid array, a row index i, and a column index j, and returns an array of the immediate neighbors (north, east, south, west) of the tile at position (i, j):

main.swift
func getImmediateNeighbors(grid: [[Int]], i: Int, j: Int) -> [Int] {
    var neighbors: [Int] = []
    let numRows = grid.count
    let numCols = grid[0].count

    // Check north neighbor
    if i > 0 {
        neighbors.append(grid[i-1][j])
    }

    // Check east neighbor
    if j < numCols-1 {
        neighbors.append(grid[i][j+1])
    }

    // Check south neighbor
    if i < numRows-1 {
        neighbors.append(grid[i+1][j])
    }

    // Check west neighbor
    if j > 0 {
        neighbors.append(grid[i][j-1])
    }

    return neighbors
}
554 chars
28 lines

You can call this function with the row and column indices of any tile in the grid to get its immediate neighbors. Note that this function assumes that the grid is rectangular (i.e. all rows have the same number of columns). If your grid is not rectangular, you may need to add some additional error checking.

related categories

gistlibby LogSnag