我如何洗牌?
How do I shuffle a list?
如何在 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
}
}
}
使用 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;
}
}
}
}
如何在 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
}
}
}
使用 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;
}
}
}
}