所以我在下面的注释代码中做了一些不言自明的练习
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更好呢?.NET是否有一种更紧凑,更有效的方法?
对于二维数组,该Length
属性返回第一维的长度乘以第二维的长度。在您的情况下,这等于2 * n
据我所知,您想要遍历第一维。
使用如下GetUpperBound
方法:
for (int i = Pairs.GetLowerBound(0); i <= Pairs.GetUpperBound(0); ++i)
{
//...
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句