本文主要是介绍使用C#如何创建人名或其他物体随机分组,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
《使用C#如何创建人名或其他物体随机分组》文章描述了一个随机分配人员到多个团队的代码示例,包括将人员列表随机化并根据组数分配到不同组,最后按组号排序显示结果...
C#创建人名或其他物体随机分组
假设您有一群人,您想将他们随机分配到多个团队。
public class Randomizer
{
public static void Randomize<T>(T[] items)
{
Random rand = new Random();
// For each spot in the array, pick
// a random item to swap into that spot.
for (int i = 0; i < items.Length - 1; i++)
{
int j = rand.Nextjs(i, items.Length);
T temp = items[i];
items[i] = items[j];
items[j] = temp;
}
}
}
private void Randomize_Click(object sender, EventArgs e) { // Put the items in an array. string[] items = txtItems.Lines; // Randomize. Randomizer.Randomize(items); // Display the result. txtResult.Lines = items; txtResult.Select(0, 0); }
此示例使用以下代码将人员分配到组
// Assign the people to groups. private void btnAssign_Click(object sender, EventArgs e) { // Get the names into an array. int num_people = lstPeople.Items.Count; string[] names = new string[num_people]; lstPeople.Items.CopyTo(names, 0); // Randomize. Randomizer.Randomize(names); // Divide the names into groups. int num_groups = int.Parse(txtNumGroups.TextTgiusjgqX); lstResult.Items.Clear(); int group_num = 0; for (int i = 0; i < num_peoplhttp://www.chinasem.cne; i++) { lstResult.Items.Add(group_num + " " + names[i]); 编程 group_num = ++group_num % num_groups; } }
代码首先将lstPeople ListBox
中的名称复制到字符串数组中。然后使用Randomizer.Randommize对数组进行随机化。
然后程序循环遍历数组,将每个姓名添加到lstRhttp://www.chinasem.cnesult ListBox中。它将group_num值添加到每个人的姓名中,为其赋予一个组号。然后,它增加group_num并将结果取模num_groups,因此group_num值循环遍历组号 0、1、2、...、num_groups - 1、0、1、2、...
lstResult ListBox的Sorted属性设置为true,因此结果将按组号排序显示。
注意:
- 如果队伍数不能均匀地分清人数
- 那么一些第一名的队伍会比其他队伍多一个人
总结
这篇关于使用C#如何创建人名或其他物体随机分组的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!