[英]Changing nested while loops to for loops… Javascript Matrix
嘿,任何人都可以將此while循環轉換為for循環。 我將非常感激,無論執行時間有多少,我都需要優化可讀性,但我們希望避免復雜性並盡可能地提高可讀性,無需多言,這里是代碼段。
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],
];
簡而言之,這是從左上角到右下角的對角線,因此無論在哪里找到“X” ,它都會增加一個否則會發現null平面counter
為零首先嵌套 while 循環用於上半對角線,第二個用於 rest
我想你正在尋找這樣的東西:
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;
}
}
此代碼段將替換所有嵌套的 while 循環。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.