数组随机化方法.转到列表
本文关键字:列表 方法 随机化 数组 | 更新日期: 2023-09-27 17:51:18
所以我一直在做一个项目,我让这个方法在一个数组中最多取16个值,并将它们随机化到一个列表中。我认为这应该是工作的,但它没有,每当它运行它崩溃的程序,但它编译得很好。
数组有" nummofteams "数量的索引
private List<string> randomizer()
{
List<string> myList = new List<string>();
Random rand = new Random();
int randomVar;
while (myList.Count < numOfTeams)
{
randomVar = rand.Next(0, numOfTeams + 1);
if (array[randomVar] != "null")
{
myList.Add(array[randomVar]);
array[randomVar] = "null";
}
}
return myList;
}
randomVar = rand.Next(0, numOfTeams);
我实现了一个洗牌列表的方法,基于d.e.k nuth的算法(Knuth shuffle或Fisher-Yates shuffle)。
也许这给了你一些提示:
public static void Shuffle<T>(IList<T> list)
{
Random rand = new Random();
int index;
T tmp;
for (int i = 1; i < list.Count; ++i)
{
index = rand.Next(i + 1);
tmp = list[i];
list[i] = list[index];
list[index] = tmp;
}
}