Fisher-Yates(java)与Collections.shuffle

时间:2017-11-23 08:00:37

标签: java arrays algorithm shuffle

我还是初学者所以请善待。我无法理解为什么Fisher-Yates算法永久地修改数组元素而Collections的shuffle方法没有。我怀疑一个原因是我可能没有真正理解Fisher-Yates算法是如何工作的,但我会感激任何帮助。代码如下:

import java.util。*;

public class ArrayShuffle {

private static char[] letters = {'a','b','c','d','e','f','g'};

public static void main(String[] args) {
    System.out.println("Collections' shuffle method:");
    shuffleCollections(letters);
    System.out.print(letters);
    System.out.println();
    System.out.println("Fisher-Yates method:");
    shuffleFisherYates(letters);
    System.out.print(letters);

}

public static void shuffleCollections(char[] abc) {
    List letterList = new ArrayList();
    for(int alph=0; alph<abc.length; alph++)
        //convert char to ArrayList object
        letterList.add(abc[alph]);
    //shuffle
    Collections.shuffle(letterList);
    System.out.println(letterList);


}

public static void shuffleFisherYates(char[] abc) {
    int size = abc.length;
    Random random = new Random();
    for(int alph=0; alph<abc.length; alph++) {
        int randomIndex = alph + random.nextInt(size - alph);
        char randomLetter = abc[randomIndex];
        abc[randomIndex] = abc[alph];
        abc[alph] = randomLetter;
    }
    for(int shuffled = 0; shuffled<abc.length; shuffled++)
        System.out.print(abc[shuffled]+" ");
    System.out.println();

}

}

1 个答案:

答案 0 :(得分:1)

您的shuffleFisherYates直接修改了输入数组(abc[someIndex] = ...;的作用)。

您的shuffleCollections根据输入数组构建ArrayList,然后修改ArrayList(通过调用Collections.shuffle(letterList))。它不会修改输入数组。