第二个数组只是随机的

时间:2017-04-02 19:26:26

标签: java arrays

我需要编写一个程序,产生数字1 - 10的单个随机排列。如果可能,没有方法或额外包含库。很简单就可以了。这是我到目前为止所拥有的。

import java.util.Scanner;
public class SwitchingNum {
public static void main(String[] args) {
    int num = 10;
    Scanner in = new Scanner(System.in);
    int[] tempArray = new int[10];
    int currentSize = tempArray.length;
    System.out.print("First Array: ");
    for(int i = 0; i < num; i++){
        tempArray[i] = i + 1;
        System.out.print(tempArray[i] + " ");
    }
    int[] permArray = new int[tempArray.length];
    System.out.println();
    System.out.print("Second Array: ");
    for (int i = 0; i < permArray.length; i ++){
        permArray[i] = tempArray[(int) (Math.random() * currentSize -1)];
        for (int j = i; j < currentSize -1; j++){
            tempArray[i] = tempArray[i+1];
        }
        currentSize--;
        System.out.print(permArray[i] + " ");
    }
}
}

1 个答案:

答案 0 :(得分:0)

调整数组的简单方法是Fisher–Yates shuffle。只需将原始数组复制到permArray,然后执行:

Random rand = new Random();
for(int i = 0;  i < permArray.length - 1; i++) {
    int swapPosition = rand.nextInt(permArray.length - i) + i;
    int tmp = permArray[i];
    permArray[i] = permArray[swapPosition]
    permArray[swapPosition] = tmp;
}

不要忘记导入java.util.Random。有关详情,请查看this question