Assign people (or anything else) to randomly selected groups in C#
Suppose you have a bunch of people and you want to randomly assign them to a number of teams. This is actually fairly easy using the Randomizer I posted in my post Randomize the items in an array in C#. See that post for information about how the Randomizer works.First, use the Randomizer to randomize the list of names. Calculate the number of people that should be in each team (call it N).Now loop through the people. Assign the first person to the first group, the second person to the second group, and so forth. When you have added one person to each group, start over adding the next person to the first group, and so forth.The following code shows how the program does its work.
// Assign the people to groups.To make viewing the results easier, the example program's result listbox displays its items in sorted order. Because the program adds the group number to the beginning of each person's name, this sorts them by group.Note that if the number of teams doesn't evenly divide the number of people, then some of the first teams will have one more person than the other teams.Download example
private void btnAssign_Click(object sender, EventArgs e)
{
// Get the names into an array.
int numPeople = lstPeople.Items.Count;
string[] names = new string[numPeople];
lstPeople.Items.CopyTo(names, 0);
// Randomize.
Randomizer.Randomize<string>(names);
// Divide the names into groups.
int numGroups = int.Parse(txtNumGroups.Text);
lstResult.Items.Clear();
int groupNum = 0;
for (int i = 0; i < numPeople; i++)
{
lstResult.Items.Add(groupNum.ToString() +
" " + names[i]);
groupNum = ++groupNum % numGroups;
}
}



Comments