How do I solve the Eloquent Javascript "Chess Board"?
It's actually pretty easy you need to make two loops, one for each row and the other for choosing the element you want to console.log (either ' ' or '#').
check the comments through solution
var size = 8; //this is the variable setting
var board = "";//this is the empty string we're going to add either ' ' , '#' or newline
for (var y = 0; y < size; y++) { /*in the outer loop we add newline to seperate rows*/
for (var x = 0; x < size; x++) {/*every inner loop rappresents a line, and alternatively it's adding either ' ' or '#' to the string that's being populated*/
if ((x + y) % 2 == 0)
board += " ";
else
board += "#";
}
board += "\n";
}
console.log(board);
Here's a different approach.
Each row has four instances of either _#
or #_
(where the underscore is a space).
Even-numbered rows begin with _#
and odd-numbered rows begin with #_
:
var chessBoard= '',
size= 8,
c;
for(var i = 0 ; i < size ; i++) {
c= i%2 ? '# ' : ' #';
for(var j = 0 ; j < size/2 ; j++) {
chessBoard+= c;
}
chessBoard+= '\n';
}
console.log(chessBoard);
jsFiddle Demo
I am a fan of chess :) In chess, there is the rule "White on right" which means that the first square of our chess board will be " ". Following that it will alternate every time there is an odd match between row and column.
var board = "";
for(var i = 0; i < 8; i++){
for(var a = 0; a < 8; a++){
board += (a % 2) == (i % 2) ? " " : "#";
}
board += "\n";
}
Viewing the board, it now shows an 8x8 grid
console.log(board);
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
Feel free to substitute i
for a row number or a
for a column number. Or set both to a size :) It will still work. For example, a < 20
will give 20 columns
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # #