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!
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With