c# - 使用随机生成灯具列表

时间:2014-12-02 22:17:38

标签: c# list random

我试图创建一个列表方法来存储灯具列表。目前我一直在我的代码的if (fixtures[i] != lineup)部分出现错误,我无法理解为什么。我不断收到以下错误。

未处理的类型' System.ArgumentOutOfRangeException'发生在mscorlib.dll

其他信息:指数超出范围。必须是非负数且小于集合的大小。

我不明白为什么这是一个问题,因为如果fixtures [i]为null,那么它应该为它添加阵容吗?

        private List<string> GenerateFixtures()
    {
        List<string> fixtures = new List<string>(); // Create a new list to store the games
        while (fixtures.Count < 7) // There can only be 6 possible games
        {
            Random random = new Random(DateTime.UtcNow.Millisecond); // Generate a new random
            int home = random.Next(0, 3); // Home team number
            int away = random.Next(0, 3); // Away team number
            if (home == away) // If they are the same teams
            {
                while (home == away) // whilst they are equal to eachother
                {
                    away = random.Next(0, 3); // generate new away team
                }
            }

            string lineup = string.Format("{0} v {1}", home, away); // convert it to a string

            for (int i = 0; i <= fixtures.Count; i++) // whilst i is 0
            {
                if (fixtures[i] != lineup) // if fixtures is not equal to lineup
                    fixtures.Add(lineup); // add it
            }

        } // loop through till it is done
        return fixtures; // then return it
    }

我也有点担心,我打算以错误的方式创造这个。我有4支球队 - 球队0,1,2,3,他们应该随机互相比赛(我随机使用,因此我总是采用不同的阵容,因为我打算将其用于其他组)。

0 v 1 || 2 v 3 || 2 v 1 || 3 v 0 || 1 v 3 || 0 v 2

有更好的方法吗?

我还注意到,我这样做的方式将允许0 v 1和1 v 0添加到列表中,因为它们是不同的。

3 个答案:

答案 0 :(得分:3)

ArgumentOutOfRangeException表示您正在尝试访问阵列外部索引的数组成员。

在这一行:

for (int i = 0; i <= fixtures.Count; i++)

您应该将<=更改为<

答案 1 :(得分:1)

出界错误的简单解决方案是从测试中删除for循环中的=符号。您正在测试包含的数量,它总是比索引高1。

将其更改为

for (int i = 0; i < fixtures.Count; i++) 

至于你的另一个问题,好像有更好的方法,这就是我如何处理问题,解决你对重复问题的担忧,以及解决你遇到的其他问题。

private List<string> GenerateFixtures(int teamCount, int matchCount)
{
    var teams = new List<int>(Enumerable.Range(0, teamCount));
    var r = new Random();

    var matchups = from t1 in teams
                   from t2 in teams.Where(t => t > t1)
                   select new Tuple<int, int, int>(t1, t2, r.Next());

    var matches = matchups.OrderBy(m => m.Item3)
                          .Take(matchCount)
                          .Select(m => string.Format("{0} v {1}", m.Item1, m.Item2))
                          .ToList();

    return matches;
}

它所做的第一件事是生成一个团队列表,用于生成所有可能的匹配排列。第一个LINQ查询生成所有可能的匹配排列,并将它们与随机数一起分配给元组。下一个LINQ查询按随机数对比赛进行排序,以保持匹配随机的要求,然后获取所需的匹配数量。然后它将这些项目投影到您正在使用的字符串格式,并将它们放在列表中。

不是这样做的唯一方法,如果您愿意,可以在一个巨大的LINQ查询中完成整个过程,但我将其分解只是为了让它更容易解释。

答案 2 :(得分:1)

您的第一次迭代将导致错误,因为没有Fixtures[0]

您需要一些确保Fixtures.Count != 0的原始代码。如果是这样(第一次迭代),请添加第一个阵容:

if (Fixtures.Count == 0) {
    Fixtures.Add(lineup);
} else {
    ...
}

希望有意义