Make random groups of people or other objects in C#

This example shows how you can 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.

    // Divide the names into groups.
    int num_groups = int.Parse(txtNumGroups.Text);
    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.

This entry was posted in algorithms, mathematics and tagged , , , , , , , , , , , , , . Bookmark the permalink.

10 Responses to Make random groups of people or other objects in C#

  1. svashta says:

    Nice example. Though, I’m stuck using it in a web form instead of a windows form. The line:
    ListBox1.Items.CopyTo(names, 0);
    throws a “At least one element in the source array could not be cast down to the destination array type.”
    error. Any solution to that?
    I would really appreciate.
    Thank you.

  2. Rod Stephens says:

    Well, that part of the program just copies the names from the first ListBox into the names array. In a real program, you’d probably want the user to type the names into a TextBox. Then you would split the text at newlines or commas or something to copy the names into the array and go from there.

    I don’t know it’s giving you that particular error. Are you putting strings in ListBox1? Or something more complex like Person objects?

  3. svashta says:

    I just needed to change the line:
    string[] names = new string[numPeople];
    ListItem[] names = new ListItem[numPeople];

    Now I’m having problems with the last part. Instead of sorting the names into groups like for example (0,0,0),(1,1,1),(2,2,2) it sorts like (0,1,2),(0,1,2),(0,1,2)..

  4. Rod Stephens says:

    That sort of makes sense. A ListBox can hold just about anything. In my example, I placed strings in it. It sounds like your code placed ListItems in it. (Or perhaps that control just does that in ASP.NET.)

    In the example program, I set the output ListBox’s Sorted property to true so it does the sorting for me. Can you do that?

    Otherwise you’ll have to place the results in an array or list and then sort them yourself.

  5. svashta says:

    the listbox doesn’t have the option ‘sorted’ so I had to add some code like you said. thanks for the help. appreciate.

  6. Rod Stephens says:

    Sorry about that. At least that explains it! 😉

  7. Ello says:
    //Global variable 
    Random r = new Random();
    private void btnAssign_Click(object sender, EventArgs e)
        //Convert listbox item to sequence of strings
        IEnumerable<string> peoples = lstPeople.Items.Cast<string>();
        //Randomize sequence and order sequence
        var query = peoples
            .OrderBy(_ => r.Next())
            .Select((people, index) => index % int.Parse(txtNumGroups.Text) + " " + people)
            .OrderBy(x => x);
        //Assign result to listbox
        lstResult.DataSource = query.ToList();
  8. Akash Sharma says:

    In previous day example you created an app that saves folder / file info in a file.
    Now we need to extend the same very app. Put another button Read Folder Info on that
    and it should read the FolderInfo.txt in all levels of folders and insert that information into
    a Dictionary<string,List>.
    Now put a textbox on the windows form and a button to search for a file name or folder
    Now user clicks on the Button and it will search the file/folder name in the whole Dictionary
    And it should Show a message Box displaying the
    Name of Folder Path and/or Name of File Path. Eg
    2 – Folder/Files Found for your search
    1. Folder – C:\A\Ram
    2. File –

    • RodStephens says:

      You should be able to do that. It will take a while to scan the entire directory hierarchy. You’ll also need to recreate at least some of the data any time it is changed if you want it to stay up-to-date.

      If the user is going to enter the full path to a folder, then you can simply use it to find the corresponding file.

      If you want to search for file names or substrings, then you may want to use a database. For example, if you want to search for all folders that contain a file that contains the string “read,” then the dictionary won’t help much.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.