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