乱序检查

来源:互联网 发布:c 五子棋源码 编辑:程序博客网 时间:2024/05/29 09:05

编写一个程序ShuffleTest,接收命令行M和N,将大小为M的数组打乱N次且在每次打乱之前都将数组重新初始化为a[i]=i。打印一个M×M的表格,对于所有的列j,行i表示的是i在打乱后落到j的位置的次数。数组中的所有元素的值都应该接近于N/M。

import edu.princeton.cs.algs4.*;public class fly {// 让数组内的每一个数与它所处位置之后的数交换来保证数组的良好随机效果// 而不是每一个数与位置前或后的数交换,以防造成重复,影响随机效果public void shuffle(int[] a) {int N = a.length;for (int i = 0; i < N; i++) {int r = i + StdRandom.uniform(N - i);int temp = a[i];a[i] = a[r];a[r] = temp;}}public void ShuffleTest(int M, int N) {int[] a = new int[M];int[][] b = new int[M][M];for (int i = 0; i < N; i++) {for (int h = 0; h < M; h++) {a[h] = h;}shuffle(a);for (int j = 0; j < M; j++) {for (int k = 0; k < M; k++) {if (j == a[k])b[j][k]++;}}}for (int i = 0; i < M; i++)for (int j = 0; j < M; j++) {StdOut.print(b[i][j] + " ");if (j == M - 1)StdOut.println();}}public static void main(String[] args) {new fly().ShuffleTest(StdIn.readInt(), StdIn.readInt());}}



0 0
原创粉丝点击