Is using Random and OrderBy a good shuffle algorithm?

前端 未结 12 1570
-上瘾入骨i
-上瘾入骨i 2020-11-21 11:41

I have read an article about various shuffle algorithms over at Coding Horror. I have seen that somewhere people have done this to shuffle a list:

var r = ne         


        
12条回答
  •  -上瘾入骨i
    2020-11-21 12:12

    This has come up many times before. Search for Fisher-Yates on StackOverflow.

    Here is a C# code sample I wrote for this algorithm. You can parameterize it on some other type, if you prefer.

    static public class FisherYates
    {
            //      Based on Java code from wikipedia:
            //      http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
            static public void Shuffle(int[] deck)
            {
                    Random r = new Random();
                    for (int n = deck.Length - 1; n > 0; --n)
                    {
                            int k = r.Next(n+1);
                            int temp = deck[n];
                            deck[n] = deck[k];
                            deck[k] = temp;
                    }
            }
    }
    

提交回复
热议问题