【问题标题】:Why is my array index out-of-bounds in this algorithm?为什么我的数组索引在此算法中超出范围?
【发布时间】:2016-03-20 20:51:45
【问题描述】:

所以我在下面的注释代码中做了一个不言自明的小练习

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{

    public static int[,] GetPairs ( int [] arr ) 
    {
        // given an array arr of unique integers, returns all the pairs
        // e.g. GetPairs(new int [] { 1, 2, 3, 4, 5 }) would return
        // { {1, 2}, {1, 3}, {1, 4}, {1, 5}, {2, 3}, {2, 4}, {2, 5}, {3, 4}, {3, 5}, {4, 5} }   

        int n = (arr.Length * (arr.Length - 1))/2; // number of pairs unique pairs in an array of unique ints
        if ( n < 1 ) return new int[0,2] {}; // if array is empty or length 1
        int[,] pairs = new int[n,2]; // array to store unique pairs
        // populate the pairs array:
        for ( int i = 0, j = 0; i < arr.Length; ++i ) 
        {
            for ( int k = i + 1; k < arr.Length; ++k )
            {
                pairs[j,0] = arr[i];
                pairs[j,1] = arr[k];
                ++j;
            }
        }
        return pairs;       
    }

    public static void Main()
    {
        int [] OneThroughFour = new int [4] { 1, 2, 3, 4 };
        int [,] Pairs = GetPairs(OneThroughFour);
        for ( int i = 0; i < Pairs.Length; ++i )
        {
            Console.WriteLine("{0},{1}",Pairs[i,0],Pairs[i,1]);
        }

    }
}

我得到的错误是

[System.IndexOutOfRangeException: 索引超出范围 数组。]

在循环中

    for ( int i = 0; i < Pairs.Length; ++i )
    {
        Console.WriteLine("{0},{1}",Pairs[i,0],Pairs[i,1]);
    }

这对我来说没有任何意义。什么是越界?当然不是i,因为它在01、...、Pairs.Length - 1 的范围内。当然不是01,因为它们是有效的索引。

另外,有没有可能比O(n^2) 做得更好,.NET 有没有更紧凑和高效的方法?

【问题讨论】:

  • Pairs.Length 不是第一个维度的长度。它是两个维度长度的乘积。
  • 试试for ( int i = 0; i &lt;= Pairs.GetUpperBound (0); ++i )

标签: c# .net arrays algorithm


【解决方案1】:

对于二维数组,Length 属性返回第一个维度的长度乘以第二个维度的长度。在你的情况下,这等于2 * n

据我所知,您想要的是遍历第一个维度。

像这样使用GetUpperBound 方法:

for (int i = Pairs.GetLowerBound(0); i <= Pairs.GetUpperBound(0); ++i)
{
    //...
}

【讨论】:

  • 好发现,Yacoub。
  • 感谢@QualityCatalyst
  • 有点不一致。使用i = GetLowerBound(0); i &lt;= GetUpperBound(0); ...i = 0; i &lt; GetLength(0); ...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-11
相关资源
最近更新 更多