這將切換其行內元素:
//input array (3X4) {{0 1 2 3} {1 4 5 6} {0 7 8 9}}
int[][] m = {{0, 1, 2, 3}, {1, 4, 5, 6}, {0, 7, 8, 9}};
for (int column = 0; column < m[0].length; column++) {
int shufcol = (int)(Math.random()*4);
int shufrow = (int)(Math.random()*3); //need row to switch with, too
for(int row = 0; row < m.length; row++) {
if(row == shufrow){
int tempField =m[row][column];
m[row][column]= m[row][shufcol];
m[row][shufcol] = tempField;
System.out.println("In row " + row + " : column " + column + " was switched with column " + shufcol + "!");
break; //just switch once per row, easier debugging ^^-d
}
}
}
//print output array
for(int row = 0; row < m.length; row++) {
String line = "\n";
for (int column = 0; column < m[0].length; column++) {
line += m[row][column] + " ";
}
System.out.print(line);
}
輸出:
In row 2 : column 0 was switched with column 2!
In row 0 : column 1 was switched with column 2!
In row 1 : column 2 was switched with column 3!
In row 0 : column 3 was switched with column 2!
0 2 3 1
1 4 6 5
8 7 0 9
既然我不能完全確定你想要做什麼,這裏是整個一個開關元件rray隨機:
//input array (3X4) {{0 1 2 3} {1 4 5 6} {0 7 8 9}}
int[][] m = {{0, 1, 2, 3}, {1, 4, 5, 6}, {0, 7, 8, 9}};
for (int column = 0; column < m[0].length; column++) {
int shufcol = (int)(Math.random()*4);
int shufrow = (int)(Math.random()*3); //need row to switch with, too
//there is no point in duplicating the count variable of a loop!
System.out.println(shufcol);
for(int row = 0; row < m.length; row++) {
//check that random field is not current field!
if(row != shufrow && column != shufcol){
//switch current with random
int temp = m[row][column]; // le backuppe
m[row][column] = m[shufrow][shufcol]; // write le new value of "random source field" to current field
m[shufrow][shufcol] = temp; // write value of current field to "random source field"
System.out.println("switched [" + row + "][" + column + "] with [" + shufrow + "]["+ shufcol + "]");
break; // use break to switch only once per row, easier debugging ^^-d
}
else {
System.out.println("will not switch with self!");
}
}
}
//print output array
for(int row = 0; row < m.length; row++) {
String line = "\n";
for (int column = 0; column < m[0].length; column++) {
line += m[row][column] + " ";
}
System.out.print(line);
}
得到以下的輸出:
2
switched [0][0] with [2][2]
0
switched [0][1] with [1][0]
0
switched [0][2] with [2][0]
2
switched [0][3] with [1][2]
8 1 0 5
1 4 3 6
2 7 0 9
希望這有助於! ^^ - d
你是什麼意思切換元素?還有......改寫? – pajton 2011-03-27 19:26:34
那麼什麼是期望的輸出? ^^ – 2016-12-09 01:51:34