[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Make random groups of people or other objects 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 at Randomize arrays in C#. See that post for information about how the Randomizer works.

This example uses the following code to assign people to groups.

// 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; } }

The code first copies the names from the lstPeople ListBox into an array of strings. It then uses Randomizer.Randommize to randomize the array.

The program then loops through the array, adding each name to the lstResult ListBox. It includes the value group_num to each person's name to give it a group number. It then increments group_num and takes the result modulus num_groups so the group_num value loops over the group numbers 0, 1, 2, ..., num_groups - 1, 0, 1, 2, ...

The lstResult ListBox's Sorted property is set to true so the result is displayed sorted by group number.

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 the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.