Reputation: 1781
I am trying to understand javascript but I can't see why wouldn't this work as a nested loop for a chess board task mentioned in javascript eloquent book. I know the solution and how to do it, but I am just wondering why the code shown below won't work. If someone could explain it. What I was expecting from this code to do is, to make a chess board, but it obviously outputs wrong.So, again I don't need a solution for a chess board, just an explanation of why is this not working. I was expecting that, var board, will get filled with empty fields when first if statement was true, and if that is false, it will get # in addition, until var x is 9, and the statement x%(width-1)==0 becomes true, it gets in to new line. But the output is not as expected. This is the code:
var height = 8;
var width = 10;
var board = "";
for (var y = 0; y < height; y++) {
for (var x = 0; x < width; x++) {
if ((x + y) % 2 == 0){
board += " ";
}
else if(x%(width-1) == 0){
board += "\n";
}
else{
board += "#";
}
}
}
console.log(board);
Upvotes: 1
Views: 2760
Reputation: 1086
Your problem is that both (x + y) % 2 == 0 and x % (width - 1) == 0 (or, simpler, x == width - 1) can hold true at the same time, so which condition check should have priority over the other?
E.g.,
if x == 9 and y == 7, then
(9 + 7) % 2 == 0
So, you should test x against its width bound first for your desired output; i.e., I'd try this, instead:
for (var y = 0; y < height; y++) {
for (var x = 0; x < width; x++)
{
if (x == width - 1) {
board += "\n";
} else if ((x + y) % 2 == 0){
board += " ";
}
else {
board += "#";
}
}
}
Upvotes: 1
Reputation: 2291
You can do it as a nested loop, but the reason for the incorrect output is because your logic is flawed.
reason 1: You actually get x%(width-1)===0 when x is 0 as well (the initialized state) so this triggers two times per inner loop.
reason 2: for every odd value that also would come at a point where x%(width-1)===0 (which again happens twice per inner loop) where there would normally be a '#', there is now a '\n'
If you fix this issue by instead changing this else if statement to:
if(x%(width-1) === 0 && x>0){
board += "\n";
}
and moving it to the last part of the inner loop, this will work. However, I'm a fan of moving the '\n' addition to the outer loop instead and then you don't need to worry about this logic at all. If you are worried about a newline not appearing before the chessboard (or after, depending on how you code it) then you can do a y>0 check for the newline addition:
var height = 8;
var width = 10;
var board = "";
for (var y = 0; y < height; y++) {
if(y>0) board += "\n";
for (var x = 0; x < width; x++) {
if ((x + y) % 2 == 0){
board += " ";
} else {
board += "#";
}
}
}
console.log(board);
Upvotes: 3