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

125
Visualizações
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 Respostas
Responde à pergunta

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