我记得看到一种方法似乎是排序,在哪里可以解开项目。
例如,我试图使用Random类显示从0到10的随机化项目。但我猜这不是最好的选择。
所以,我想为IEnumberable,List或数组创建一个扩展,无论什么都是最好的方法。
答案 0 :(得分:16)
您正在寻找一个随机播放,随机重新排序的一个好例子是Fisher-Yates Shuffle。
答案 1 :(得分:7)
看起来像冒泡排序的算法将是:
for i= 0:(len(x)-1):
j = random(i,len(x)-1)
swap(x[i],x[j])
假设random(a,b)返回一个随机整数c,使得< = c< = b。
并且,该算法被称为“Fisher Yates Shuffle”。
FWIW,您无法使用标准的内置随机数生成器“真正”洗牌。 21项shuffle具有65位的熵,其中大多数RNG是64位或32位。
答案 2 :(得分:0)
这将为您提供0到10之间的随机值(包括10):
int[] randomNumbers = Shuffle(Enumerable.Range(0, 11), new Random()).ToArray();
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source, Random random)
{
T[] list = source.ToArray();
int count = list.Length;
while (count > 1)
{
int index = random.Next(count--);
T temp = list[index];
list[index] = list[count];
list[count] = temp;
}
return list;
}
答案 3 :(得分:-3)
你可以使用linq ...
var result = Enumerable.Range(0,10).OrderBy( n=> Guid.NewGuid() )
答案 4 :(得分:-3)
有趣的问题, 我建议离开工作林:
IEnumerable<int> list = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
Random rnd = new Random();
list = list.Select(i => new { value = i, rank = rnd.Next(list.Count()) }).OrderBy(n => n.rank).Select(n => n.value);