'Javascript Chessboard Print

I am learning how to code in Javascript and one of the exercises I am trying to solve is how to print out a chessboard to the console to make it look like this:

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

I was able to do this using two for-loops, but I want to do it using just one for-loop to make it more efficient. This is what I have so far:

var x = "#";

for(var i = 1; i < 65; i++) {


 if((i%9 == 0)) {
    x = "\n" + x.charAt(i-1);
  }

  else if (x.charAt(i-1) == "#") {
        x = x + " "
  }

  else {
    x = x + "#";
  }
}

console.log(x);

This is only posting one "#", and I am not sure why. Any help is appreciated!



Solution 1:[1]

Ooooooh, codegolf !

var x = new Array(33).join('#').split('').map(function(e,i) {
    return (i % 4 == 0 ? (i === 0 ? '' : '\n') + (i % 8 ? ' ' : '') : ' ') + e;
}).join('');

document.body.innerHTML = '<pre>' + x + '</pre>'; // for code snippet stuff !

To fix your original function, you have to actually add to the string, and by using '\n' + x.charAt(i-1); you're getting a newline and a single character, as that's what charAt does, it gets a single character at that index, so you're string never goes beyond having one single #.

var x = "#";

for (var i = 1; i < 65; i++) {
    if (i % 9 == 0) {
        x += "\n";
    } else if (x[x.length-1] == "#") {
        x += " "
    } else {
        x += "#";
    }
}

That solves that, but it still doesn't stagger the pattern, you'd need additional logic for that

Solution 2:[2]

Think about what happens when you call this line:

x = "\n" + x.charAt(i-1);

You make x into a newline with addition of a SINGLE character. Do you see why your string isn't long now?

Solution 3:[3]

use :

        x = x + "\n" + x.charAt(i-1);

instead of

x ="\n" + x.charAt(i-1);

To get the exact pattern you have to add some extra logic to your code.

Solution 4:[4]

Please see my solution, it uses loop inside loop and is rather simple. In addition you can put any width-length of the chessboard:

// define variable for grid size 
const size = 8;
// outer loop handles the quantity of lines
for (let i = 1; i <= size; i++) {
    // define sting variable for line
    let line = "";
    // inner loop handles what characters will be in line
    for (let j = 1; j <= size; j++) {
        // check what character to start with: space or #
        // to take into account both loops check if sum of i and j is even or not
        (j + i) % 2 === 0 ? line += "#" : line += " ";
    }
    // print the line and go to next line using "\n" symbol
    console.log(line + "\n");
}

Solution 5:[5]

//create a variable and assign a space to it
let result = " ";
//create a nested for loop for the 8 X 8 tiles.
 for (let x = 0; x < 8; x++){
    for (let z = 0; z < 8; z++){
//Replace each even character by space
      if (0 == (z + x) % 2){
        result += " ";
      } else if (0 != (z + x) % 2){
//otherwise replace each odd character by a "#"
        result += "#";
      }   
    }    
//to keep each line blocks of 8, use \n 
    result += "\n";
} 
//to print in a straight line, console.log outside the forloop 
console.log(result);

Solution 6:[6]

 let size = 8, result= '';
    for(let i=0; i < size; i++) { 
      for(let j=0; j < size; j++) {
          if(i !== 0 && j === 0 ) {
          result += '\n';
          }
          if( (i%2 === 0 && j%2 === 0) || (i%2 ===1 && j%2 === 1)) {
           result += ' ';
          } else if( (i%2 !== 0 && j%2 === 0) || (i%2 === 0 && j%2 !== 0)) {
            result += '#';
          }
      }
    }
    
    console.log(result);

Here, I have just learn :).

Solution 7:[7]

I did it like this:

let chess = "";

for (i = 1; i < 9; i += 1) {
  for (j = 1; j < 9; j += 1) {
    if (i % 2 == 0) {
      if (j % 2 == 0) {
        chess = chess + "#";
      } else {
        chess = chess + " ";
      }
    } else if (i % 2 !== 0) {
      if (j % 2 == 0) {
        chess = chess + " ";
      } else {
        chess = chess + "#";
      }
    }
  }
  chess = chess + "\n";
}
console.log(chess);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Dair
Solution 3
Solution 4 Vladyslav Klymenko
Solution 5 Sambydev
Solution 6
Solution 7 Shima_S