如何在C#中均匀地分享随机数字

时间:2018-06-13 16:26:20

标签: c# arrays random count counter

我正在寻找在不同人群之间分享固定数量的32支队伍。

当然,32可能并不总是可以被整除,但是为了这个练习,让我说我想分享4人之间的32支球队,所以每人最多可以有8支球队。

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

现在,我可以运行该代码,我将获得随机选择的人员及其团队的列表。但是限制将不会实施,一些球员最终会有更多的球队。

我理解以下代码:

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

无法累计用户收到的团队数量,我是否在正确的轨道上如何计算玩家被随机选择的次数或是否有另一种方法我应该在做什么?

2 个答案:

答案 0 :(得分:1)

代码中的一个问题是你在循环内初始化计数器。如果计数[选择]&gt;会发生什么?最大?你离开团队,不要把它分配给任何其他人。

请尝试以下代码。

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

答案 1 :(得分:0)

我无法计算你的代码,但这应该有效。

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;
}
相关问题