0

目标是创建从 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)));
4

0 回答 0