Today I went through a standard coding challenge: “Create a minesweeper board with variable rows, columns, and bombs”. The challenge was for 20 minutes, spent 31 minutes, and cannot really figure out why it could never generate.
After my previous posting of “omg my server didn’t have virtual memory” I decided to fiddle it out. With my own fingers this took 12 minutes tops, but the amount of regret I feel is priceless.
function makeMinesweeperBoard(rows = 5, cols = 5, mines = 5) {
var board = [];
/* Make a blank board with 0s */
for (let r = 0; r < rows; r++) {
let l = new Array();
for (let c= 0 ; c < cols; c++) {
l.push('0');
}
board.push(l);
}
/* Fill board with mines, aka Xs */
while (mines > 0) {
let c = Math.floor(Math.random() * cols);
let r = Math.floor(Math.random() * rows);
if (board[r][c] == 'X') { continue; }
board[r][c] = 'X';
mines--;
}
/* Put the numbers where they need to be */
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
if (board[r][c] == 'X') { continue; }
let totalMines = 0;
for (let x = -1; x <= 1; x++) {
for (let y = -1; y <= 1; y++) {
if ((r + x) < 0) { continue; }
if ((c + y) < 0) { continue; }
if ((r + x) >= rows) { continue; }
if ((c + y) >= cols) { continue; }
if (board[r + x][c + y] == "X") {
totalMines++;
}
}
}
board[r][c] = totalMines.toString();
}
}
return board;
}
console.log(makeMinesweeperBoard());
The first mistake was in board/array generation. The clue was specifically on the screen in that an array of Objects were created when I needed an array of arrays. I also misused Array.prototype.fill() in my derpiness and ended up on Round 2 just hand-pushing my 0s.
Second mistake was on mine laying. I didn’t check if the space actually had a mine or not, so when actually generating a specific number of mines it had a 1 in rows*cols chance of duplicating.
Third mistake was in the mine counting. I made my tester aware that it would exceed array bounds and I felt a bit under pressure (since time was ticking down) to remedy it.
Regardless it took me less than 20 minutes to jsfiddle this solution together with my own fingers and console.log()’s.