【发布时间】: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,因为它在0、1、...、Pairs.Length - 1 的范围内。当然不是0 或1,因为它们是有效的索引。
另外,有没有可能比O(n^2) 做得更好,.NET 有没有更紧凑和高效的方法?
【问题讨论】:
-
Pairs.Length不是第一个维度的长度。它是两个维度长度的乘积。 -
试试
for ( int i = 0; i <= Pairs.GetUpperBound (0); ++i )