0

我如何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
        }
    }
}
4

1 回答 1

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;
            }
        }
    }
}
于 2020-01-16T19:48:17.720 回答