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

129
Vistas
Fill matrix with snake pattern using javascript

I want to fill in a 2D array of numbers with snake pattern, I tried this algorithm but the result it's not the expected:

function fill2d(c,l) {
    var arr = new Array[l][c];

    let counter = 0;
    for (let col = 0; col < arr.l; col++) {
        if (col % 2 == 0) {
            for (let row = 0; row < arr.l; row++) {
                arr[row][col] = counter++;
            }
        } else {
            for (let row = arr.length - 1; row >= 0; row--) {
                    arr[row][col] = counter++;
                }
            }
        }
            return arr;

    }

fill2d(4,4)

some thing like that :

 1  2  3  4
 8  7  6  5
 9 10 11 12
16 15 14 13
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Okay so basically all you need is to traverse row-by-row but alternating between left-to-right and right-to-left. Here's my solution:

function fill2d(c, l) {
  let arr = new Array(l);
  for (var i = 0; i < l; i++) {
    arr[i] = new Array(c);
  }

  let count = 1;
  for (let i = 0; i < l; i++) {
    console.log("i: ", i);
    let right_to_left = i % 2;
    for (let j = (right_to_left * (l - 1));
      (right_to_left ? (j >= 0) : (j < c)); j += (right_to_left ? -1 : 1)) {
      console.log("j: ", j);
      arr[i][j] = count++;
    }
  }
  return arr;
}

console.log(fill2d(4, 4));

Also, you weren't allocating a 2d array properly, you need to allocate a 1d array first and then allocate an array for each of the elements of that array.

Note: I added logs for each i and j so that you can see how the array is traversed.

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