-1

so im working on a function or a solution for this problem but im still a junior. this is the provided array, [javascript] **

[ 
  [0, 9, 0, 0],
  [0, 0, 9, 0],
  [0, 9, 0, 9],
  [9, 9, 0, 0],
  ]

new

  [1, 9, 2, 1],
  [2, 3, 9, 2],
  [3, 9, 4, 9],
  [9, 9, 3, 1],
]
**

im starting a minesweeper project, the zeros are empty spaces , the 9's are mines, i need to change the zeros to the number of adjacent mines, i couldnt find a simple solution that i could understand , so if someone can provide a simple solution i would appreciate it. i thought about getting the coordinates [x-1][y-1], [x][y-1] [x] [y+1] etc.. for each index but the thing is not every index has these coordinates. help plz

1 Answers1

1

You just need to go to all 8 positions (pos) below snippet and need to check if they are in scope of correct index(because they can go below 0 and more than 3 as per your 2-d array).

const arr = [
  [0, 9, 0, 0],
  [0, 0, 9, 0],
  [0, 9, 0, 9],
  [9, 9, 0, 0],
];

const pos = [
  [-1, -1],
  [-1, 0],
  [-1, 1],
  [0, -1],
  [0, 1],
  [1, -1],
  [1, 0],
  [1, 1],
];

const result = [];

for (let i = 0; i < arr.length; ++i) {
  result.push([]);
  for (let j = 0; j < arr[i].length; ++j) {
    if (arr[i][j] === 0) {
      let count = 0;

      pos.forEach(([x, y]) => {
        const newX = i + x;
        const newY = j + y;
        if (
          newX >= 0 &&
          newY >= 0 &&
          newX < arr[i].length &&
          newY < arr.length
        ) {
          // console.log(newX, newY, arr[newX][newY]);
          if (arr[newX][newY] && arr[newX][newY] === 9) ++count;
        }
      });
      result[i][j] = count;
    } else {
      result[i][j] = arr[i][j];
    }
  }
}

console.log(result);
DecPK
  • 24,537
  • 6
  • 26
  • 42