【问题标题】:Shuffle an array around in this specific way? [duplicate]以这种特定方式随机排列数组? [复制]
【发布时间】:2013-04-04 18:00:16
【问题描述】:

我想要做的是每次加载我的控制台应用程序时随机播放下面的数组。例如,蝙蝠侠每次都可以在 name[1]name[2]name[3] 旁边,而不是“name[0]”。

            heroes[] names = new heroes[4];

            names[0] = batman;              
            names[1] = ironman;             
            names[2] = hulk;
            names[3] = flash;

怎么做?

【问题讨论】:

  • 您可能会使用Fisher-Yates Shuffle/Knuth ShuffleThis 是一个 C# 实现,但如果您进行搜索,这个地方应该有几个......
  • Jared Butler,我已经从帖子中删除了所有“感谢信”/“我正在学习”文字......但我没有看到任何关于你的洗牌的“具体”内容。如果您愿意,请随时恢复我的更改,但请务必解释您需要什么“特定”方式来洗牌元素。否则,它与非常流行的问题(上图)重复。

标签: c# arrays random shuffle


【解决方案1】:

使用列表和这种扩展方法:

public static class ListExtensions
{
    /// <summary>
    /// Shuffle algorithm as seen on page 32 in the book "Algorithms" (4th edition) by Robert Sedgewick
    /// </summary>
    public static void Shuffle<T>(this IList<T> source)
    {
        var n = source.Count;
        for (var i = 0; i < n; i++)
        {
            // Exchange a[i] with random element in a[i..n-1]
            var r = i + RandomProvider.Instance.Next(0, n - i);
            var temp = source[i];
            source[i] = source[r];
            source[r] = temp;
        }
    }
}

public static class RandomProvider
{
    [ThreadStatic]
    public static readonly Random Instance;

    static RandomProvider()
    {
        Instance = new Random();
    }
}

【讨论】:

    【解决方案2】:
            heroes[] names = new heroes[4];
            names[0] = batman;
            names[1] = ironman;
            names[2] = hulk;
            names[3] = flash;
    
            var rnd = new Random(DateTime.Now.Second);
            for (int i = 0; i < heroes.Length; i++)
            {
                names[i] = heroes[rnd.Next(0, heroes.Length - 1)];
            }
    

    这应该为您指明正确的方向。

    【讨论】:

    • 这很有可能会包含两次相同的名称而漏掉一个。
    • @KonradRudolph 请做扩展,像这样简单的笼统陈述没有任何好处。
    • 糟糕,不,我明白我做了什么:P
    • 删除了我的其他评论 - 再看一遍,我不知道这是在做什么。第二个数组名称heroes 未定义,但这要么会随机重复名称并将名称排除在外,要么会将已分配的名称归零。很难说英雄数组/列表没有定义。
    • 以扑克牌为例,随机选择 N 张牌但不移除它们(你在做什么)与洗牌并拿 N 张牌是不同的。
    猜你喜欢
    • 1970-01-01
    • 2019-08-02
    • 2022-06-28
    • 1970-01-01
    • 1970-01-01
    • 2015-05-23
    • 2014-05-21
    • 2021-07-28
    • 1970-01-01
    相关资源
    最近更新 更多