Javascript Chessboard Print

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.

Tags:

Javascript