Why is my array index out-of-bounds in this algorithm?

Viewed 98

So I'm doing a little practice that is self-explanatory in the commented code below

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]);
        }

    }
}

and the error I'm getting is

[System.IndexOutOfRangeException: Index was outside the bounds of the array.]

in the loop

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

which doesn't make any sense to me. What is out-of-bounds? Surely not the i, for it is in the range 0, 1, ..., Pairs.Length - 1. Surely not the 0 or 1, for those are valid indices.

Also, is it possible to do this better than O(n^2) and is there a way with .NET that is more compact and efficient?

1 Answers
Related