animesh.blog

Chess board problem

Chess board problem from chapter 2 of Eloquent Javascript book.

Problem statement

Write a program that creates a string that represents an 8×8 grid, using newline characters to separate lines. At each position of the grid there is either a space or a “#” character. The characters should form a chess board.

Passing this string to console.log should show something like this:

 # # # #
# # # #
 # # # #
# # # #
var charToShow = 'X';

function printChessBoard(size) {
    var res = '',
        i, j,
        space = ' ';

    for (i = 0; i < size; i++) {
        res = '';
        for (var j = 0; j < size; j++) {
            if (i % 2 === 0) {
                res += space + charToShow;
            } else {
                res += charToShow + space;
            }
        }
        console.log(res);
    }
}