c# - 为什么我的数组索引在此算法中越界?

标签 c# .net arrays algorithm

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

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: Index was outside the bounds of the array.]

在循环中

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

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

此外,是否有可能比 O(n^2) 做得更好? .NET 有没有一种更紧凑、更高效的方法?

最佳答案

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

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

使用 GetUpperBound像这样的方法:

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

关于c# - 为什么我的数组索引在此算法中越界?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36119426/

相关文章:

c# - Windows 服务在特定分钟内每小时运行一次

c# - 如何让 JObject.FromObject(object) 包含类型信息?

.net - 为什么我不能为Silverlight和通常的.NET创建程序集?

.net - 中继命令和无参数执行方法

javascript - 我可以将数组转换为 Promise 数组吗?

c# - 从 C# 发送邮件时使用 To 或 CC - 在性能方面哪个更好?

c# - Parallel.ForEach错误

.net - msdeploy 忽略 .hgignore

arrays - d3.selectAll 输入嵌套键值对的导出——又名 : how do array selections work?

arrays - Matlab 将向量转换为二进制矩阵