Sobes.tech
Middle+

How would you search for neighbors if you implemented a game board using a one-dimensional array instead of a two-dimensional one?

sobes.tech AI

Answer from AI

If the game board is stored in a one-dimensional array, then to find neighbors, you need to know the width of the board (for example, width). Then the position of a cell with coordinates (x, y) corresponds to the index index = y * width + x.

To find neighbors, you need to calculate the indices of neighboring cells considering the boundaries of the board:

  • Left neighbor: index - 1 (if x > 0)
  • Right neighbor: index + 1 (if x < width - 1)
  • Top neighbor: index - width (if y > 0)
  • Bottom neighbor: index + width (if y < height - 1)

If diagonal neighbors are needed, add:

  • Top-left: index - width - 1 (if x > 0 and y > 0)
  • Top-right: index - width + 1 (if x < width - 1 and y > 0)
  • Bottom-left: index + width - 1 (if x > 0 and y < height - 1)
  • Bottom-right: index + width + 1 (if x < width - 1 and y < height - 1)

Example in JavaScript:

function getNeighbors(index, width, height) {
  const x = index % width;
  const y = Math.floor(index / width);
  const neighbors = [];

  if (x > 0) neighbors.push(index - 1); // left
  if (x < width - 1) neighbors.push(index + 1); // right
  if (y > 0) neighbors.push(index - width); // top
  if (y < height - 1) neighbors.push(index + width); // bottom

  // Diagonals
  if (x > 0 && y > 0) neighbors.push(index - width - 1); // top-left
  if (x < width - 1 && y > 0) neighbors.push(index - width + 1); // top-right
  if (x > 0 && y < height - 1) neighbors.push(index + width - 1); // bottom-left
  if (x < width - 1 && y < height - 1) neighbors.push(index + width + 1); // bottom-right

  return neighbors;
}

Thus, by using index arithmetic and boundary checks, you can efficiently find neighbors in a one-dimensional array.