我需要一个扩展方法来洗牌IEnumerable<T>
。它还可以采取int
指定返回的大小IEnumerable
。更好地保持不变性IEnumerable
。我目前的解决方案IList
-
public static IList<T> Shuffle<T>(this IList<T> list, int size)
{
Random rnd = new Random();
var res = new T[size];
res[0] = list[0];
for (int i = 1; i < size; i++)
{
int j = rnd.Next(i);
res[i] = res[j];
res[j] = list[i];
}
return res;
}
public static IList<T> Shuffle<T>(this IList<T> list)
{ return list.Shuffle(list.Count); }
您可以使用Fisher-Yates-Durstenfeld 洗牌。无需显式地将大小参数传递给方法本身,您只需添加对Take如果您不需要整个序列:
var shuffled = originalSequence.Shuffle().Take(5);
// ...
public static class EnumerableExtensions
{
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source)
{
return source.Shuffle(new Random());
}
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source, Random rng)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (rng == null) throw new ArgumentNullException(nameof(rng));
return source.ShuffleIterator(rng);
}
private static IEnumerable<T> ShuffleIterator<T>(
this IEnumerable<T> source, Random rng)
{
var buffer = source.ToList();
for (int i = 0; i < buffer.Count; i++)
{
int j = rng.Next(i, buffer.Count);
yield return buffer[j];
buffer[j] = buffer[i];
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)