欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 游戏 > 使用C#创建人名或其他物体随机分组

使用C#创建人名或其他物体随机分组

2025/5/7 6:31:48 来源:https://blog.csdn.net/ljygood2/article/details/144682642  浏览:    关键词:使用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.Next(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.Text);lstResult.Items.Clear();int group_num = 0;for (int i = 0; i < num_people; i++){lstResult.Items.Add(group_num + " " + names[i]);group_num = ++group_num % num_groups;}
}

代码首先将lstPeople ListBox 中的名称复制到字符串数组中。然后使用Randomizer.Randommize对数组进行随机化。

然后程序循环遍历数组,将每个姓名添加到lstResult ListBox中。它将group_num值添加到每个人的姓名中,为其赋予一个组号。然后,它增加group_num并将结果取模num_groups,因此group_num值循环遍历组号 0、1、2、...、num_groups - 1、0、1、2、...

lstResult ListBoxSorted属性设置为true,因此结果将按组号排序显示。

注意,如果队伍数不能均匀地分清人数,那么一些第一名的队伍会比其他队伍多一个人。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词