如何随机播放列表?

时间:2020-01-16 19:48:17

标签: list random beef

如何在牛肉中洗净List?我想在Random上添加一个扩展,就地改写List

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 个答案:

答案 0 :(得分:0)

使用Fisher-Yates随机播放算法:

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