tsaiDavid tsaiDavid - 6 months ago 37
Javascript Question

How do I solve the Eloquent Javascript "Chess Board"?

new coder here trying to learn JS. I did codecademy already and am working through Eloquent Javascript now. I finally got something together after scratching my head for a very long while... but it doesn't work! I'm not quite sure if I'm approaching this from the right angle but I do know I want to use the loops to track progress through the printing of the # based grid.


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:


# # # #
# # # #
# # # #
# # # #
# # # #
# # # #


My code is below:

var chessBoard = "";
var size = 8;

for (var lineCounter = 1; lineCounter < size; lineCounter++) {

if (lineCounter%2 === 0) { /

/if lineCounter is an even number
for (var charCounter = 1; charCounter < size; charCounter++) {
var evenOdd = (charCounter%2 === 0);
switch (evenOdd) {
case true:
(chessBoard += "#");
break;
case false:
(chessBoard += " ");
break;
}
}
}
else { //if lineCounter is an odd number
for (var charCounter = 1; charCounter < size; charCounter++) {
var evenOdd = (charCounter%2 === 0);
switch (evenOdd) {
case true:
(chessBoard += " ");
break;
case false:
(chessBoard += "#");
break;
}
}
}
chessBoard += "\n";
}
console.log(chessBoard);


The current output of the program is this:

# # # #
# # #
# # # #
# # #
# # # #
# # #
# # # #


Through some iterations, I've already learned a lot, but right now I already see an error - I'm clearly down to a 7x7 grid instead of the 8x8 I wanted to get. I suspect it has to do with me using "<" in my for loops, but not sure if there's a better way to tackle this instead of just adding an extra digit.

Answer

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);