【发布时间】: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