listrandombeef

How do I shuffle a list?


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
        }
    }
}

Solution

  • 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;
                }
            }
        }
    }