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

Assuming that the grid is a 2D array and you have the coordinates of tile n, you can find its immediate neighbors (north, east, south, west) in the following way:

index.tsx
function getImmediateNeighbors(grid, x, y) {
  const neighbors = [];

  // Check north neighbor
  if (y > 0) {
    neighbors.push(grid[x][y - 1]);
  }

  // Check east neighbor
  if (x < grid.length - 1) {
    neighbors.push(grid[x + 1][y]);
  }

  // Check south neighbor
  if (y < grid[0].length - 1) {
    neighbors.push(grid[x][y + 1]);
  }

  // Check west neighbor
  if (x > 0) {
    neighbors.push(grid[x - 1][y]);
  }

  return neighbors;
}

// Example usage
const grid = [
  [0, 1, 2, 3, 4],
  [5, 6, 7, 8, 9],
  [10, 11, 12, 13, 14],
  [15, 16, 17, 18, 19],
  [20, 21, 22, 23, 24],
];
const neighbors = getImmediateNeighbors(grid, 2, 2);
console.log(neighbors); // [7, 13, 17, 11]
691 chars
37 lines

This function takes the grid as a 2D array, and the x and y coordinates of the tile you want to find the neighbors of. It returns an array containing the immediate neighbors of that tile. The function checks each of the four possible directions and adds the neighbor to the array if it exists. If it doesn't exist (i.e., at the edge of the grid), that direction is skipped.

related categories

gistlibby LogSnag