Search code examples
javascriptarraysmultidimensional-arrayminesweeper

JavaScript: 2D Array Minesweeper accessing neighbors to += 1 them


So I have an input 2D array with already placed mines in it:

const input = [
  [0, 0, '*'],
  ['*', 0, 0],
  [0, '*', 0]
];

What I need to do it's to output changed 2D array with added number to neighbors, but I don't know how can I elegantly access them.

const mineSweeper = (input) => {
  for (let row = 0; row < input.length; row++) {
    for (let col = 0; col < input[row].length; col++) {
      if (input[row][col] === '*') {
        // How can I access neighbors from here elegantly?
      }
    }
  }
}

The output should look like that:

const output = [
  [1, 2, '*'],
  ['*', 3, 2],
  [2, '*', 1]
];

Any tip? Thanks.


Solution

  • You can use double nested map to get each element and then you can create another function that will take current index of row and column and check the close * of each element.

    const input = [
      [0, 0, '*'],
      ['*', 0, 0],
      [0, '*', 0]
    ]
    
    function count(data, i, j) {
      let c = 0;
    
      const prevRow = data[i - 1];
      const currentRow = data[i]
      const nextRow = data[i + 1];
    
      [prevRow, currentRow, nextRow].forEach(row => {
        if (row) {
          if (row[j - 1] == '*') c++;
          if (row[j] == '*') c++;
          if (row[j + 1] == '*') c++;
        }
      })
    
      return c;
    }
    
    function update(data) {
      return data.map((a, i) => {
        return a.map((b, j) => {
          return b == '*' ? b : count(data, i, j)
        })
      })
    }
    
    const result = update(input)
    console.log(result)