【问题标题】:Changing nested while loops to for loops… Javascript Matrix将嵌套的 while 循环更改为 for 循环... Javascript 矩阵
【发布时间】:2021-03-30 03:01:01
【问题描述】:

大家好,任何人都可以将此 while 循环转换为 for 循环。我将非常感激,无论执行时间有多少,我都需要优化可读性,但我们希望避免复杂性并尽可能提高可读性,无需多言,这里是 sn-p。

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

输出

OutputMatrix = [
  [1, 1, 0, 0],
  [0, 2, 2, 1],
  [0, 0, 3, 3],
  [1, 1, 0, 0],
];

简而言之,这是从左上角到右下角的对角线,因此无论在哪里找到 "X",它都会增加一,否则会发现 null flat counter 到零第一个嵌套while循环用于上半对角线,第二个用于其余部分

【问题讨论】:

    标签: javascript arrays for-loop matrix while-loop


    【解决方案1】:

    我认为您正在寻找这样的东西:

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

    这个 sn-p 将替换所有嵌套的 while 循环。

    【讨论】:

    • 非常感谢,这是我最好的sn-p
    猜你喜欢
    • 2018-08-13
    • 2017-09-26
    • 1970-01-01
    • 1970-01-01
    • 2014-03-15
    • 2020-09-17
    • 1970-01-01
    • 2022-01-19
    • 2013-10-26
    相关资源
    最近更新 更多