lundi 23 novembre 2020

Placing bombs in minesweeper - deduce probability of mine on cell in loop

I am rebuilding minesweeper, and have created the following function to create the initial grid stucture:

const rows = 10
const columns = 10
const bombs = 10

const grid = range(rows).map(() =>
  range(columns).map(() => ({
    hasFlag: false,
    hasBomb: false,
    isOpen: false,
  })))

let bombsSet = 0

while (bombsPlaced < bombs) {
  const rowNumber = Math.floor(Math.random() * rows)
  const columnNumber = Math.floor(Math.random() * columns)
  grid[rowNumber][columnNumber].hasBomb = true

  bombsSet = grid.flat().filter(({ hasBomb }) => hasBomb).length
}

While this technically works just fine, it seems "suboptimal" in that the while loop may end up performing a hasBomb = true assignment on the same cell multiple times, simply due to whatever Math.random() spits out.

It seems like there would be a way to generate the probability of whether a not a cell should be hasBomb = true inside the initial range(columns).map function, where the two numbers relevant are the number of cells left, and the number of bombs left to set.

For example, inside the loop, if we had 3 bombs left to set, and 4 cells left to go, we would have some percent chance of whether or not that cell needs to be a bomb.

However, I can't quite work out how to arrange the arithmetic. Any help would be appreciated.




Aucun commentaire:

Enregistrer un commentaire