0

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

1 Answer 1

1

I think you are looking for something like this:

for (i = 0; i < rows; i++) {
    for (j = 0; j < cols; j++) {
        if (Matrix[i][j] == "X") {
            // If positioned on top row OR left column of matrix -> first X on diagonal
            if (i == 0 || j == 0) OutputMatrix[i][j] = 1;
            // Else: previous element on diagonal + 1
            else OutputMatrix[i][j] = OutputMatrix[i-1][j-1] + 1;
        }
        else OutputMatrix[i][j] = 0;
    }
}

This snippet will replace all the nested while loops.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much this was the best snippet in my case

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.