目标是创建一个从0到N-1的M个整数的随机样本。
我在网上找到了这个代码(http://introcs.cs.princeton.edu/java/14array/Sample.java.html)
int M = Integer.parseInt(args[0]); // choose this many elements
int N = Integer.parseInt(args[1]); // from 0, 1, ..., N-1
int[] perm = new int[N];
for (int i = 0; i < N; i++)
perm[i] = i;
// create random sample in perm[0], perm[1], ..., perm[M-1]
for (int i = 0; i < M; i++) {
int r = i + (int) (Math.random() * (N-i));
int t = perm[r];
perm[r] = perm[i];
perm[i] = t;
}
for (int i = 0; i < M; i++)
System.out.print(perm[i] + " ");
System.out.println();
我不明白使用数组的必要性,只需4行即可。
int M = Integer.parseInt(args[0]); // choose this many elements
int N = Integer.parseInt(args[1]); // from 0, 1, ..., N-1
for(int i=0; i<M; i++)
System.out.println(i + (int) (Math.random() * (N-i)));