Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Chessboard Print

Tags:

javascript

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!

like image 921
vibhu1201 Avatar asked Nov 10 '14 07:11

vibhu1201


People also ask

What is chessboard JS?

chessboard. js is a standalone JavaScript Chess Board. It is designed to be "just a board" and expose a powerful API so that it can be used in different ways.


3 Answers

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

like image 87
adeneo Avatar answered Oct 19 '22 20:10

adeneo


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?

like image 27
Dair Avatar answered Oct 19 '22 20:10

Dair


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.

like image 5
Suchit kumar Avatar answered Oct 19 '22 20:10

Suchit kumar