How do I shuffle a list?

39 Views Asked by At

How do I shuffle a List in Beef? I would like to add an extension to Random that shuffles a List in-place:

using System.Collections.Generic;

namespace System
{
    extension Random 
    {
        public virtual void Shuffle<T>(List<T> list)
        {
            // Use this to shuffle the list in-place
        }
    }
}
1

There are 1 best solutions below

0
On BEST ANSWER

Use the Fisher-Yates shuffle algorithm:

using System.Collections.Generic;

namespace System
{
    extension Random 
    {
        public virtual void Shuffle<T>(List<T> list)
        {
            for (let i = list.Count - 1; i > 0; i--) 
            {
                let j = Next(0, i + 1);
                let tmp = list[j];
                list[j] = list[i];
                list[i] = tmp;
            }
        }
    }
}