Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

415
Visualizações
Is there a better way to make a chessboard in Javascript?

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 :)

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório

0

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"))

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda