Kris Bond
Kris Bond

Reputation: 3

How to share random numbers out evenly in C#

I am looking at sharing out a fixed number of 32 teams between a varied number of people.

Of course, 32 may not always be evenly divisible, but for the sake of this exercise, lets say I am looking to share the 32 teams between 4 people, so a maximum number of 8 teams per person.

int max = 32 / numb;

foreach (string value in wcteams)
{
    //Assigning teams to players
    int selection = random.Next(0, numb);

    int[] counter = new int[max];
    counter[selection] = counter[selection] + 1;

    if (counter[selection] < max)
    {
        Console.WriteLine(inputtedNames[selection] + " has drawn " + value);
    }                    
}

Right now, I can run that code and I will get a list back of randomly chosen people along with their team. But the limit will not be implemented and some players will end up with more teams than others.

I understand that the following code:

counter[selection] = counter[selection] + 1;

Is not working to add up the number of teams that the user has received, am I on the right track here with how to tally up the number of times a player has been randomly selected or is there another method that I should be doing?

Upvotes: 0

Views: 90

Answers (2)

Harsh Shah
Harsh Shah

Reputation: 678

One problem in your code is you are initializing counter inside the loop. Also what happens if the count[selection] > max? you leave the team and don't assign it to anyone else.

Try the following code.

int numb = 4;
int max = 32 / numb;
int[] counter = new int[max];
foreach (string value in wcteams)
{
    bool selectionComplete = false;
    while(!selectionComplete)
    {
        int selection = random.Next(0, numb);
        counter[selection] = counter[selection] + 1;

        if (counter[selection] <= max)
        {
            selectionComplete = true;
            Console.WriteLine(selection + " has drawn " + value);
        }  
    }                      
}

Upvotes: 1

paparazzo
paparazzo

Reputation: 45096

I cannot figure your code but this should work.

public static Random randomT = new Random();
public static List<List<string>> DivideTeams(string[] teams, int personCount)
{
    List<List<string>> divideTeams = new List<List<string>>();
    if (teams.Length % personCount != 0)
    {
        throw new ArgumentOutOfRangeException();
    }
    //shuffle teams 
    for(int k = teams.Length -1; k > 0; k--)
    {
        int trade = random.Next(k + 1);
        string temp = teams[trade];
        teams[trade] = teams[k];
        teams[k] = temp;
    }
    for (int j = 0; j < personCount; j++)
    {
        divideTeams.Add(new List<string>());
        for (int i = 0; i < teams.Length / personCount; i++)
        {
            divideTeams[j].Add(teams[i]);
        }
    }           
    return divideTeams;
}

Upvotes: 0

Related Questions