Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

419
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda