algs4 实验题1.1.36 乱序检查
//实验题 1.1.36 乱序检查
//实验题 1.1.36 乱序检查
public class ShuffleTest {
public static void shuffle(int[] a) {
int M = a.length;
for (int i = 0; i < M; i++) {
int r = i + StdRandom.uniform(M-i);
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
//打印一个 M * M 的表格
public static void show(int[][] A) {
int M = A.length;
for (int i = 0; i < M; i++) {
for (int j = 0; j < M; j++) {
StdOut.print(A[i][j] + " ");
}
StdOut.println();
}
}
public static void main(String[] args) {
//初始命令行参数 M,N
int M = Integer.parseInt(args[0]);
int N = Integer.parseInt(args[1]);
int[][] count = new int[M][M]; //记录i在打乱后落在位置j的次数
for (int i = 0; i < M; i++) //初始化二维矩阵;
for (int j = 0; j < M; j++) {
count[i][j] = 0;
}
int[] a = new int[M];
//将大小为M的数组a打乱N次
for (int n = 1; n <= N; n ++ ) { // 打乱N次
for (int i = 0; i < M; i ++) {// 每次打乱前,数组重新初始化
a[i] = i;
}
//打乱a
shuffle(a);
//记录 i 打乱后落到j的位置次数
for (int i = 0; i < M; i ++) {
for (int j = 0; j < M; j++) {
if (i == a[j]) count[i][j]++;
}
}
}
show(count);
}
}
M = 10, N = 100
% java ShuffleTest 10 30 的结果
14 9 7 11 9 12 12 9 9 8
11 15 7 5 10 12 10 8 10 12
8 12 5 14 9 10 11 12 11 8
11 11 15 9 9 7 9 7 9 13
9 6 14 13 8 13 9 11 10 7
10 7 14 6 12 10 7 17 11 6
9 9 5 16 8 11 13 6 11 12
12 6 7 9 17 10 5 11 14 9
9 12 8 10 7 11 12 11 8 12
7 13 18 7 11 4 12 8 7 13