2014-12-02 36 views
0

我試圖創建存儲固定裝置的清單列表方法。目前我一直在我的代碼的if (fixtures[i] != lineup)部分出現錯誤,我不能解釋爲什麼。我不斷收到以下錯誤。C# - 生成固定裝置的列表,使用隨機

類型「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和他們應該隨機對手(我使用隨機,以便其總是不同的陣容,因爲我打算用於其他組)。

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

有沒有更好的方式來做到這一點?

我也剛剛注意到,我這樣做的方式將允許0 v 1和1 v 0被添加到列表中,因爲它們是不同的。

+0

你到底想幹什麼?創建一個沒有重疊對的列表?使用簡單的算法,比如鴿子而不是做隨機,你會更好。 – Codeman 2014-12-02 22:21:09

+0

在循環外部移動創建Random。你可能會得到重複,只需要創建一次。 – 2014-12-02 22:22:27

回答

1

您的第一次迭代將導致錯誤,因爲沒有Fixtures[0]

您需要一些確保Fixtures.Count != 0的原始碼。如果是這樣(第一次迭代),加上在第一陣容:

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

希望是有道理的

3

ArgumentOutOfRangeException表示您嘗試訪問數組之外​​的索引的數組成員。

在此行中:

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

你應該改變<=<

1

爲出界錯誤的簡單的解決方法是刪除等號(=)在從測試迴路。您正在測試包括哪些總是高於有指數的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查詢中完成,但我分手了,只是爲了讓它更容易解釋。