2012-07-31 81 views
0

Techies-- 此代碼適用於具有單個通道或具有均勻分割的情況。它差不多的作品,當我有餘數...因爲它會創建下一個通道,它會拉入物品,但然後超出範圍。這些線是麻煩的心臟:超出範圍的二維數組

items_per_batch = batchcount/(int)channels; // 
    subsets = batch.Split(items_per_batch); 

items_per_batch真的是用來給分割擴展通用一些關於有多少項目由分裂的想法。如果它看到一個餘數,它只是創建另一個子集數組。我真正需要做的是跟蹤項目的長度。我試過了:

int idx2 = subset.GetLength(1) 

在一個點上,但是使用該值的forloop也超出了範圍。任何人有任何建議?

static void channelassign() 
    { 
     int THRESHOLD = 2; 
     string[] batch = new string[] 
     { "item1", "item2", "item3", "item4","item5","item6","item7" }; 
     int batchcount = batch.Count(); 
     int items_per_batch; 
     string[][] subsets; 
     int idx1; 
     int idx2; 


     if (THRESHOLD != 0) //avoid accidental division by 0. 
     { 

      float channels = batchcount/THRESHOLD; 
      if (channels < 1) 
      { 
       channels = 1; // only 1 channel is needed 
       items_per_batch = batchcount; // process all items 
       idx1 = 1; // fix value to a single channel 
       idx2 = (batchcount - 1); // true start of array is 0 
       subsets = batch.Split(batchcount); //splits correctly 
      } 
      else 
      { 
       // decide how many items will be included per batch 
       channels = (int)Math.Round(channels, 
        MidpointRounding.ToEven); //determines channel number 
       items_per_batch = batchcount/(int)channels; // 
       subsets = batch.Split(items_per_batch); 
       idx1 = subsets.GetLength(0); // gets channel# assigned by split 
       // idx2 = subsets.GetLength(1); // gets items back from splits 

      } 

      //distribute contents of batch amongst channels 


      for (int channel = 0; channel < idx1; channel++) 
      { 
       for (int i = 0; i < items_per_batch; i++) 
       { 
        Console.WriteLine(" Channel:" + channel.ToString() + " 
         ItemName: {0} ", subsets[channel][i]); 
       } 
      } 


     } 
     else 
     { 
      Console.WriteLine("Threshold value set to zero. This 
       is an invalid value. Please set THRESHOLD."); 
     } 
+0

我在代碼中看到不少於*三個不同的變量命名約定。說實話有點兒精神分裂症。 – 2012-07-31 18:03:09

+0

不知道正在使用Split擴展方法,或者您爲其提供源代碼;你還沒有提供任何東西給任何人去... – 2012-07-31 18:07:59

回答

2

該科int s的執行

float channels = batchcount/THRESHOLD; 

,所以你float channels總是有一個整數值,等於

floor(batchcount/THRESHOLD) 

但是,這不是你的問題的原因,那是

for (int channel = 0; channel < idx1; channel++) 
{ 
    for (int i = 0; i < items_per_batch; i++) 

如果batchcount不是channels的倍數,則某些頻道的項數少於items_per_batch。因此內循環嘗試訪問不存在的subsets[channel][i]

+0

真的夠了 - 我想我可以控制內部循環:idx2的值從第二維返回,但這並不奏效。你有什麼建議控制第二個循環? – plditallo 2012-07-31 18:12:12

+0

'for(int i = 0; i 2012-07-31 18:13:29

+0

我已經失去了主意!這是一個鋸齒狀的dd陣列。 idx2永遠不會解決這個問題!是的,就是這樣! – plditallo 2012-07-31 18:38:06