Hey I am new to javascript. I have just started reading Eloquent Javascript by Marin Haverbeke and I finished the chessboard problem in chapter 2 but I was wondering if my solution is good enough. I tried making the chessboard with nested loops but I am not very familiar with Javascript so I decided to only use one loop. I believe it is a faster solution because it runs in O(n) time where n is the size of the n x n board.
const boardSize = 8;
for (let i = 0; i < boardSize / 2; i++) {
console.log(" #".repeat(boardSize / 2));
console.log("# ".repeat(boardSize / 2));
}
You can change the boardSize so it will work for any size board. Output looks something like this:
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
Please let me know if this is cheating or if it is an acceptable solution. All advice is apprenciated :)
Your solution is perfectly acceptable.
You could also aim to call console.log only once, and avoid even that remaining for loop:
const boardSize = 8;
const row = " #".repeat(boardSize / 2);
const doublerow = row + "\n" + row.slice(1) + " \n";
console.log(doublerow.repeat(boardSize / 2).slice(0, -1));
Unless boardsize could have any value, the time complexity is irrelevant. But if larger sizes are allowed, then your solution is still O(n²) since that is the amount of characters it outputs. Specifically, the repeat method does not run in constant time if the argument is variable.
A chessboard has 64 squares. How about only one console.log
const boardSize = 4;
const board = [];
for (let i = 0; i < boardSize; i++) {
board.push("⬛⬜".repeat(boardSize));
board.push("⬜⬛".repeat(boardSize));
}
console.log(board.join("\n"))