【问题标题】:C#: How should I go about shuffling contents of an array?C#:我应该如何改组数组的内容?
【发布时间】:2016-09-25 06:46:25
【问题描述】:

我有一个整数数组,称为卡片[52]。每个元素都包含一个表示卡片的整数(例如,cards[0] = 5 将表示 6 个俱乐部)。

这就是我洗牌数组的方式。它有效,但我得到重复。

private void shuffleCards()
    {
        for (int i = 0; i < cards.Length; i++)
        {
            int randIndex = r.Next(0, 52);
            int origCard = cards[i];
            cards[i] = cards[randIndex];
            cards[randIndex] = origCard;
        }
    }

r 是我在程序开始时初始化的随机变量。

在测试程序时,我注意到我会得到同一张卡 2 或 3 次。显然我不能重复,它们都必须不同。我无法以任何方式看到这种方法如何让我重复。

如何在不重复的情况下随机播放此数组?谢谢。

编辑

好的,结果是随机播放功能不是问题所在。导致问题的是 deal() 函数。

private void deal()
    {
        for (int i = 0; i < 26; i++)
        {
            userCards[i] = cards[i];
            setUserValue(); //ignore this
        }
        for (int i = 26; i < 52; i++)
        {
            opponentCards[i - 26] = cards[i];
            setOpponentValue(); //ignore this
        }
    }

我确定这不是随机播放功能。我将所有卡片的结果打印到一个文本文件中,但没有看到任何迭代。然而,当牌被发给用户和对手时,所有的迭代都发生了。有什么建议吗?

【问题讨论】:

  • 要么移除已抽出的牌以免重复,要么存储已抽出的牌并将其与当前抽出的牌进行比较,然后抽一张新牌或您选择的牌。 (这句话画得太多了)
  • 随机化函数可能会产生重复的数字,所以不要尝试用其他方式交换元素
  • 你如何确定有重复?你是如何填充数组的?为什么不创建卡片类型?
  • 好的。所以你已经证明洗牌后的牌没有重复,你如何查看两只手来确定它们有重复? setUserValuesetOpponentValue 是做什么的?

标签: c# arrays random shuffle playing-cards


【解决方案1】:

有一种非常简单的算法称为Fisher Yates shuffling 算法,它在O(n) 时间和O(1) 空间复杂度中进行洗牌。

使用随机函数从给定集合生成随机索引,并将生成的随机元素替换为最后一个索引。递减最后一个索引并继续对其余元素进行此类操作。

设大小为 n 的数组为:arr[n]

void randomize ( int arr[], int n )
{
    // Use a different seed value so that we don't get same
    // result each time we run this program
    srand ( time(NULL) );

    // Start from the last element and swap one by one. We don't
    // need to run for the first element that's why i > 0
    for (int i = n-1; i > 0; i--)
    {
        // Pick a random index from 0 to i
        int j = rand() % (i+1);

        // Swap arr[i] with the element at random index
        swap(&arr[i], &arr[j]);
    }
}

来源:Algorithm

【讨论】:

    猜你喜欢
    • 2021-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多