Hey guys can anyone please convert this while loop to for loop. I will really appreciate it, i nedd to optimise readability no matter how much is the execution time but we want to avoid complexity and having increased readability as much as possible without further ado here is the snippet.
let Matrix = [
["X", "X", null, null],
[null, "X", "X", "X"],
[null, null, "X", "X"],
["X", "X", null, null],
];
let rows = 4, cols = 4;
// this is making an array of 4 arrays inside of it filled with null as initial values
let OutputMatrix = [...new Array(rows).keys()].map((x) =>
[...new Array(rows).keys()].map((i) => (i = i = null))
);
//i goes from last row to first row.
let counter = 1,
i = rows - 1,
j = 0,
k = 1;
while (i >= 0) {
while (i < rows && j < rows) {
if (Matrix[i][j] != "X") {
counter = 0;
}
OutputMatrix[i][j] = counter++;
i++, j++;
}
j = 0;
++k;
i = rows - k;
}
//j goes from second column to last column
(i = 0), (j = 1), (k = 1), (counter = 1);
while (j < cols) {
while (i < rows && j < cols) {
if (Matrix[i][j] != "X") {
counter = 0;
}
OutputMatrix[i][j] = counter++;
i++, j++;
}
i = 0;
k++;
j = k;
}
console.log(OutputMatrix);
output
OutputMatrix = [
[1, 1, 0, 0],
[0, 2, 2, 1],
[0, 0, 3, 3],
[1, 1, 0, 0],
];
in short this is going diagonal top-left to bottom-right so wherever it finds an "X" it increments by one otherwise found null flat counter to zero first nested while loop is for the upper half diagonal and the second is for the rest