如何洗牌列表< T> [英] How to shuffle a List<T>

查看:126
本文介绍了如何洗牌列表< T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现这块的Java code在维基百科应该洗牌到位的数组:

I found this piece of Java code at Wikipedia that is supposed to shuffle an array in place:

public static void shuffle (int[] array)
{
    Random rng = new Random();
    int n = array.length;
    while (n > 1) 
    {
        n--;  
        int k = rng.nextInt(n + 1);
        int tmp = array[k];
        array[k] = array[n];
        array[n] = tmp;
    } 
}

虽然我没有测试code,它看起来像它应该只是罚款阵列。在我的C#项目中,我创建了一个 CardSet 类,并使用上述code在随机播放()方法:

Though I didn't test the code, it looks like it should work just fine with an array. In my C# project I created a CardSet class and used the above code in a Shuffle() method:

public class CardSet
{
    private List<Card> cards;

    public Card this[int i]
    {
        get {  return cards[i];  }
        set {  cards[i] = value;  }
    }

    public void Shuffle()
    {
        Random rng = new Random();
        int n = this.NumberOfCards;

        while (n < 1)
        {
            n--;
            int k = rng.Next(n + 1);
            Card tmp = this[k];
            this[k] = this[n];
            this[n] = tmp;
        }
    }

在我使用的方法,但是,没有洗牌发生的情况:

When I use the method, however, no shuffling happens:

CardSet cs = new CardSet();
cs.Shuffle(); 

foreach (Card c in cs)
{
    Console.WriteLine(c.ToString());
}

我只是不明白,为什么它不工作。我认为,名单可能是自动分拣的对象,所以我试图改变它的价值之一,

I just can't figure out why it doesn't work. I thought that the List might be automatically sorting its objects, so I tried changing one of its values,

cs[8] = new Card(Suites.Hearts, Numbers.Two);

正是我放哪儿了。无论我做了一些简单的错误,或者我没有正确地写入洗牌算法。如果code我提供很好看,有人认为这个错误可能是其他地方在我的code,我可以提供我的code中的其余部分。

and that Card was exactly where I put it. Either I made some simple mistake or I didn't write the shuffling algorithm correctly. If the code I supplied looks good and someone thinks the mistake might be somewhere else in my code, I can supply the rest of my code.

推荐答案

修改

while (n < 1)

while (n > 1)

这篇关于如何洗牌列表&LT; T&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆