当前位置: 代码网 > it编程>编程语言>C# > 使用C#如何创建人名或其他物体随机分组

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

2025年02月14日 C# 我要评论
c#创建人名或其他物体随机分组假设您有一群人,您想将他们随机分配到多个团队。public class randomizer{ public static void randomize<t&

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,因此结果将按组号排序显示。

注意:

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

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com