第八章第十八题(打乱行)(Disorganize)
-
*8.18(打乱行)编写一个方法,使用下面的方法头打乱一个二维int型的行:
public static void shuffle(int[][] m)
编写一个测试程序,打乱下面的矩阵:
int[][] m = {{1,2},{3,4},{5,6},{7,8},{9,10}};
*8.18(Disorganize)Write a method to scramble a two-dimensional int line with the following method header:
public static void shuffle(int[][] m)
Write a test program to disrupt the following matrix:
int[][] m = {{1,2},{3,4},{5,6},{7,8},{9,10}}; -
参考代码:
package chapter08; public class Code_18 { public static void main(String args[]){ int[][] m = {{1,2},{3,4},{5,6},{7,8},{9,10}}; shuffle(m); for(int i = 0; i < m.length; ++i){ for(int j = 0; j < m[i].length; ++j){ System.out.print(m[i][j] + " "); } System.out.println(); } } public static void shuffle(int[][] m){ int xlen = m.length; int ylen = m[0].length; for(int i = 0; i < xlen; ++i){ for(int j = 0; j < ylen; ++j){ int n = (int)(Math.random()*ylen); int temp = m[i][n]; m[i][n] = m[i][j]; m[i][j] = temp; } int q = (int)(Math.random() * xlen); int[] temp1 = m[q]; m[q] = m[i]; m[i] = temp1; } } }
-
结果显示:
1 2 6 5 10 9 8 7 3 4 Process finished with exit code 0