最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript Chessboard Print - Stack Overflow

programmeradmin8浏览0评论

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!

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!

Share Improve this question asked Nov 10, 2014 at 7:19 vibhu1201vibhu1201 1438 bronze badges
Add a ment  | 

7 Answers 7

Reset to default 9

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

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?

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.

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

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

 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 :).

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);
发布评论

评论列表(0)

  1. 暂无评论