Skip to content

洗牌算法需要改善 #3

Description

@xiaolinli123

以下洗牌算法的代码

for (int i = 0; i < 1; i++) {
            int a = random.nextInt(54);
            int b = random.nextInt(54);
            Card temp = card[a];
            card[a] = card[b];
            card[b] = temp;
   }

注意我将200 改为了1,即只是洗了一次牌。

重复1000局游戏,就有1000把按您的洗牌方式得到的牌堆。1000把统计每一个位置(第1-54个位置)每张牌出现的次数,其结果为.csv文件:

output.csv

分析数据得到以下

Image

该结果说明洗的牌:在 95% 置信水平下,卡方统计量 (χ² = 55546.88, df = 54*54),χ²显著大于2933.4137526616146 说明数据不是均匀分布。

该算法在不当的设置下洗牌次数是1次或几次时χ²显著大于合理的值。

经典的算法:

public static void fisherYatesShuffle(String[] arr) {
        Random random = new Random();
        int len = arr.length;
        for (int i = len - 1; i > 0; i--) {
            int j = random.nextInt(i + 1);
            String temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }
    }

该算法就算只洗了一次,也接近均匀分布。

洗了200次的话,两种算法其结果都接近均匀分布。

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions