嗨我想在控制檯上使用二維數組創建一個矩陣。我們的想法是,輸出應該是這樣的一個:JAVA:如何創建一個蛇形狀矩陣
1|8|9 |16
2|7|10|15
3|6|11|14
4|5|12|13
有沒有誰擁有一個想法,它是如何做到的任何一個?
嗨我想在控制檯上使用二維數組創建一個矩陣。我們的想法是,輸出應該是這樣的一個:JAVA:如何創建一個蛇形狀矩陣
1|8|9 |16
2|7|10|15
3|6|11|14
4|5|12|13
有沒有誰擁有一個想法,它是如何做到的任何一個?
很少有東西可以從矩陣猜測: -
首先,你必須先移動到下一列
二之前遍歷列的所有行,則需要在每次迭代中在downwards
和upwards
之間交替
因此,您需要兩個嵌套循環,用於遍歷特定列的行。其中一個將從row 0 to max - 1
開始,而下一個將從row = max - 1 to 0
開始。
現在,要交替迭代方向,可以使用布爾變量,並在內循環每次迭代完成後切換它。
每個循環都需要包含在if-else
的內部。他們兩人將在一定條件下執行。如果boolean downwards = false;
,則循環向上移動將被執行,反之亦然。
在每次迭代時,用整數計數器填充當前單元格,您必須用1
進行初始化,並在每次填充後對其進行增加。
僞代碼: -
// Initialize variables row, col, and count = 1
boolean goDown = true;
int[][] matrix = new int[row][col]; // declare matrix
for i = 0 to col:
if (goDown)
for j = 0 to row: // Move in downwards direction
assign count++ to matrix[j][i]
// assign to `[j][i]` because, we have to assign to rows first
goDown = false; // Toggle goDown
else
for j = row - 1 to 0: // Move in upwards direction
assign count++ to matrix[j][i]
goDown = true; // toggle goDown
}
只是一些僞代碼,希望它有幫助,並給你一些開始。
boolean goUp = false;
boolean goDown = true;
size = 4;
matrix[size][size];
k = 0;
l =0;
loop i->0 i < size*size i++
matrix[l][k] = i;
if(l==size and goDown)
goDown = false;
goUp = true;
k++;
else if(l==0 and goUp)
goDown = true;
goUp = false;
k++;
else
l = l+ (1*goDown?1:-1);
end loop;
。
int a = 4;
int b = 4;
int c = 1;
boolean direction = true;
int[][] arrey = new int[a][b];
for (int y = 0; y <= b - 1; y++) {
if (direction) {
for (int x = 0; x <= a - 1; x++) {
arrey[x][y] = c;
c++;
}
direction = false;
} else {
for (int x = a - 1; x >= 0; x--) {
arrey[x][y] = c;
c++;
}
direction = true;
}
}
for (int x = 0; x <= a - 1; x++) {
for (int y = 0; y <= b - 1; y++) {
System.out.print("["+arrey[x][y]+"]");
}
System.out.println("");
}
很好,您成功地將我的僞代碼轉換爲真正的代碼。 :) –
但理想情況下,您應該接受幫助您獲得此解決方案的答案。但是,這也是你的選擇。你總是可以回答自己的問題並接受它。 –
因爲接受幫助你的答案是感謝這篇文章。我只是告訴你這個只是爲了你的好處。並不是說我會爲此做出代表。但是,假設你繼續這樣做,在某個時候,你將停止對你的回答收到良好的迴應。 –
標籤是作爲功課,不要指望人們爲你解決它。你有什麼嘗試? – user219882
您最後需要2個for-loops。你有什麼嘗試? – Mirco
我想,它可以通過一個'for'循環和幾個'if'語句來解決 – svz