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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

坐井观老天

您的鼓励是我分享的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值