0

技术人员——当我有一个单一的频道或当我有一个偶数分割时,这个代码就可以工作。当我有剩余时,它几乎可以工作......因为它会创建下一个频道,它会拉入项目,但随后会超出范围。这些行是问题的核心:

    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.");
        }
4

1 回答 1

2

float channels = batchcount / THRESHOLD;

ints 上执行,所以你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]不存在的 a。

于 2012-07-31T18:09:40.673 回答