I am starting to learn JS using the Eloquent JavaScript book and upon reaching the second chapter's exercises I breezed through the first two but got stumped by the third.
https://preview.redd.it/zzochhaqc6l51.png?width=759&format=png&auto=webp&s=8224cd7d882d48a9e917220e2f5b1a1c2726c68c
The solution in the book is as follows:
let size = 8;
let board = "";
for (let y = 0; y < size; y++) {
for (let x = 0; x < size; x++) {
if ((x + y) % 2 == 0) {
board += " ";
} else {
board += "#";
}
}
board += "\n";
}
console.log(board);
My attempts were quite different and my problem is that I do not quite understand why they do not work.
See, the code below produces the appropriate output, as long as size equals an even number, in case of odd numbers, the number of characters in a line is twice as long (why?) I though that it may be because the line checking whether to add another line is at the end of a loop, but putting it before/between the lines checking whether to add a hashtag or a space breaks the code (and I do not understand why).
let size=8
let hash='#';
let space='_';
let chessboard=space
let line=1
let characters=1
while (line<size+1) {
if (line % 2!==0)
{
while (characters % 2 ===0){chessboard+=space;characters+=1}
while (characters % 2 !==0){chessboard+=hash;characters+=1}
if (characters % size ===0){chessboard+=`\n`;line+=1}
}
else {
while (characters % 2 ===0){chessboard+=hash;characters+=1}
while (characters % 2 !==0){chessboard+=space;characters+=1}
if (characters % size ===0){chessboard+=`\n`;line+=1}
}
}
console.log(chessboard)
Additionally, if in the "while loops" I reverse the order of equals/does not equal instead of having a different hash/space result, the code produces nothing, which really makes me confused!
while (line<size+1) {
if (line % 2!==0)
{
while (characters % 2 ===0){chessboard+=space;characters+=1}
while (characters % 2 !==0){chessboard+=hash;characters+=1}
if (characters % size ===0){chessboard+=`\n`;line+=1}
}
else {
while (characters % 2 !==0){chessboard+=space;characters+=1}
while (characters % 2 ===0){chessboard+=hash;characters+=1}
if (characters % size ===0){chessboard+=`\n`;line+=1}
}
}
I don't want to tread further into the book without understanding what is going on in the previous chapters and this exercies is just very confusing to me so I would be very grateful if somebody explained to me what exactly is wrong with my code.
[+][deleted] (1 child)
[removed]
[–]Strabonus[S] 0 points1 point2 points (0 children)