Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

124
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!