Is using Random and OrderBy a good shuffle algorithm?

前端 未结 12 1553
-上瘾入骨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条回答
  •  无人共我
    2020-11-21 12:07

    Looking for an algorithm? You can use my ShuffleList class:

    class ShuffleList : List
    {
        public void Shuffle()
        {
            Random random = new Random();
            for (int count = Count; count > 0; count--)
            {
                int i = random.Next(count);
                Add(this[i]);
                RemoveAt(i);
            }
        }
    }
    

    Then, use it like this:

    ShuffleList list = new ShuffleList();
    // Add elements to your list.
    list.Shuffle();
    

    How does it work?

    Let's take an initial sorted list of the 5 first integers: { 0, 1, 2, 3, 4 }.

    The method starts by counting the nubmer of elements and calls it count. Then, with count decreasing on each step, it takes a random number between 0 and count and moves it to the end of the list.

    In the following step-by-step example, the items that could be moved are italic, the selected item is bold:

    0 1 2 3 4
    0 1 2 3 4
    0 1 2 4 3
    0 1 2 4 3
    1 2 4 3 0
    1 2 4 3 0
    1 2 3 0 4
    1 2 3 0 4
    2 3 0 4 1
    2 3 0 4 1
    3 0 4 1 2

提交回复
热议问题