Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 529
tsaiDavid Avatar asked May 13 '15 21:05

tsaiDavid


6 Answers

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

 # # # # # # # # # #
# # # # # # # # # # 
 # # # # # # # # # #
# # # # # # # # # # 
 # # # # # # # # # #
# # # # # # # # # # 
 # # # # # # # # # #
# # # # # # # # # # 
like image 112
Travis J Avatar answered Oct 05 '22 05:10

Travis J


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);
like image 35
maioman Avatar answered Oct 05 '22 06:10

maioman


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);
like image 26
Rick Hitchcock Avatar answered Oct 05 '22 07:10

Rick Hitchcock


Here's a version

console.log((new Array(65).join().split("")).map( function(v,i) {
    return ( (i/8 >> 0 ) % 2 ? ( i%2 ? " " : "#") : (i%2 ? "#" : " ") ) +
           ( (i+1) %8 ? "" : "\n" );
}).join(""));
like image 37
Tero Tolonen Avatar answered Oct 05 '22 06:10

Tero Tolonen


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);
like image 37
Karl Mendes Avatar answered Oct 05 '22 06:10

Karl Mendes


Using only the knowledge provided up to that point in the book Eloquent JavaScript here is my solution:

   var board = "";
   var size = 8;

   // Outer for loop creates a new line** after each cycle of the inner for loop
   for (var lineCount = 0; lineCount < size; lineCount++) {
       //The nested for loop adds a character to the board variable on a single line proportional to the size variable
       for (var spaceCount = 0; spaceCount < size; spaceCount++) {
           //This if statement creates the offset lines in the example image by alternating the first character depending on the lineCount
           if (lineCount % 2 == 0) {
               var black = "#",
                   white = " ";
           } else {
               black = " ";
               white = "#";
           }
           if (spaceCount % 2 == 0) {
               board += white;
           } else {
               board += black;
           }
       }
       board += "\n"; //** new line created
   }
   console.log(board);
like image 38
Noah Johnson Avatar answered Oct 05 '22 07:10

Noah Johnson