java - Fisher-Yates (java) 与 Collections.shuffle

标签 java arrays algorithm shuffle

我还是个初学者,所以请多关照。我很难理解为什么 Fisher-Yates 算法会永久修改数组元素,而 Collections 的 shuffle 方法却不会。我怀疑原因之一是我实际上可能没有正确理解 Fisher-Yates 算法的工作原理,但我将不胜感激任何帮助。代码如下:

导入 java.util.*;

公共(public)类 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();

}

最佳答案

您的 shuffleFisherYates 直接修改输入数组(这就是 abc[someIndex] = ...; 所做的)。

您的 shuffleCollections 基于输入数组构建一个 ArrayList,然后修改该 ArrayList(通过调用 Collections.shuffle (字母表))。它不会修改输入数组。

关于java - Fisher-Yates (java) 与 Collections.shuffle,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47450305/

相关文章:

algorithm - 将网格划分为矩形

java - log4j 与 Mac OS Leopard 兼容吗

java - 使用 StanfordCoreNLP 时出错

javascript - 在 React 中使用数组设置状态

arrays - 如何解析字段名称中具有随机哈希值的golang json数组

c++ - 查找要删除重复项的项目

android - 在 Eclipse 中手动设置 JDK 路径

java - 如何配置 Spring 使用 @RequestBody 注释将 JSON 反序列化为 BigDecimal

java - 首先从第二维填充 List<List<Integer>>

algorithm - 没有洗牌的分区总和