Skip to main content
1 of 2
Mike Brant
  • 9.6k
  • 13
  • 23

I would consider building the board as a separate concern from displaying the board.

I would also encourage you to more heavily leverage Array() functions

function buildBoard(size) {
    var board = Array(size);
    for (var row = 0; row < size; row++) {
        board[row] = Array(size).fill(0);
        for (var col = row % 2; col < size; col = col + 2) {
            board[row][col] = 1;
        }
    }
    return board;
}

function displayBoard(size) {
    var board = buildBoard(size);
    var output = '';
    board.forEach(function(row) {
        row.forEach(function(col) {
           output += (col === 1) ? '#' : ' ';
        });
        output += "\n";
    });
    console.log(output);
}

displayBoard(8);
        

Now this certainly is not optimized from the standpoint of of operational complexity (in that you have to perform \$O(n^2)\$ iteration twice, but it does break down the problem into the logic space of setting up a board and then displaying a board.

Mike Brant
  • 9.6k
  • 13
  • 23