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 listbox的sorted属性设置为true,因此结果将按组号排序显示。
注意:
- 如果队伍数不能均匀地分清人数
- 那么一些第一名的队伍会比其他队伍多一个人
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论