Minesweeper

Given a number of rows, columns, and mines, create a minesweeper board. Print the board where each mine is shown as an “X”.

const makeBoard = (rows, cols, mines) => {
  let board = initBoard(rows, cols)
  board = plantMines(rows, cols, board, mines)
  board = plantMinesCount(rows, cols, board)
  return board
}

const initBoard = (rows, cols) => {
  let board = []

  for (let i = 0; i < rows; i++) {
    board[i] = new Array(cols)

    for (let j = 0; j < cols; j++) {
      board[i][j] = 0
    }
  }

  return board
}

const plantMines = (rows, cols, board, mines) => {

  while (mines) {
    const r = randomNum(rows)
    const c = randomNum(cols)

    if (board[r][c] !== -1) {
      board[r][c] = -1
      mines -= 1
    }
  }

  return board
}

const plantMinesCount = (rows, cols, board) => {
  for (let i = 0; i < rows; i++) {
    for (let j = 0; j < cols; j++) {
      board = countAdjacentMines(i, j, board)
    }
  }

  return board
}

const countAdjacentMines = (row, col, board) => {
  if (board[row][col] == -1) {
    return board
  }

  const rowAbove = row - 1
  const rowBelow = row + 1
  const colLeft  = col - 1
  const colRight = col + 1

  const adjacent = [
    [rowAbove, colLeft],
    [rowAbove, col],
    [rowAbove, colRight],
    [row, colLeft],
    [row, colRight],
    [rowBelow, colLeft],
    [rowBelow, col],
    [rowBelow, colRight]
  ]

  let count = 0

  for (let i = 0; i < adjacent.length; i++) {
    const coordinates = adjacent[i]
    const r = coordinates[0]
    const c = coordinates[1]

    if (r >= 0 && r < board.length && c >= 0 && c < board[r].length) {
      if (board[r][c] == -1) {
        count += 1
      }
    }
  }

  board[row][col] = count

  return board
}

const drawBoard = (board) => {
  const rows = board.length
  const cols =  board[0].length
  let output = ""

  for (let i = 0; i < rows; i++) {
    for (let j = 0; j < cols; j++) {
      const value = board[i][j]

      if (value == -1) {
        output += " X"
      }
      else {
        output = output + " " + value
      }
    }

    output += "\n"
  }

  return output
}

const randomNum = (max) => {
  return Math.floor(Math.random() * max)
}

const board = makeBoard(5, 5, 5)
const drawn = drawBoard(board)

console.log(board)
console.log(drawn)

Here is the output:

[
  [ 2, -1, 3, 2, -1 ],
  [ 3, -1, 4, -1, 2 ],
  [ 2, -1, 3, 1, 1 ],
  [ 1, 1, 1, 0, 0 ],
  [ 0, 0, 0, 0, 0 ]
]
 2 X 3 2 X
 3 X 4 X 2
 2 X 3 1 1
 1 1 1 0 0
 0 0 0 0 0
Scroll to top