alexx0186
alexx0186

Reputation: 1567

How can I go through every diagonal of a 2D array in C#?

I have an array of type int[5,6]. :

   abcdef
   bcdefg
   cdefgh
   defghi
   efghij

I want to add up the values to each other, like: myArray[1,2]+ myArray[2,1], or myArray[1,3]+ myArray[2,2]+ myArray[3,1]

How can I go through it in this fashion:

a
bb
ccc
dddd
eeeee
ffffff
ggggggg

.. and so on?

Upvotes: 0

Views: 481

Answers (1)

ASh
ASh

Reputation: 35722

generic solution

public static IList<IList<T>> GetSecondaryDiagonals<T>(this T[,] array2d)
{
    int rows = array2d.GetLength(0);
    int columns = array2d.GetLength(1);

    var result = new List<IList<T>>();            

    // number of secondary diagonals
    int d = rows + columns - 1;
    int r, c;

    // go through each diagonal
    for (int i = 0; i < d; i++)
    {
        // row to start
        if (i < columns)
            r = 0;
        else
            r = i - columns + 1;
        // column to start
        if (i < columns)
            c = i;
        else
            c = columns - 1;

        // items from diagonal
        var diagonalItems = new List<T>();
        do
        {
            diagonalItems.Add(array2d[r, c]);
            r++;
            c--;
        } 
        while (r < rows && c >= 0);
        result.Add(diagonalItems);
    }

    return result;
}

example of usage

private static void Main()
{
    var T1 = new char[,] // more rows than columns
        {
            {'a', 'b', 'd'},
            {'c', 'e', 'g'},
            {'f', 'h', 'j'},
            {'i', 'k', 'l'},
        };

    var T2 = new int[,] // more columns than rows
        {
            {1, 2, 4, 7},
            {3, 5, 8, 0},
            {6, 9, 1, 2},
        };

    Print(T1.GetSecondaryDiagonals());
    Print(T2.GetSecondaryDiagonals());
    Console.ReadKey();
}

static void Print<T> (IList<IList<T>> list)
{
    Console.WriteLine();
    foreach (var sublist in list)
    {
        foreach (var item in sublist)
        {
            Console.Write(item);
            Console.Write(' ');
        }
        Console.WriteLine();
    }
}

output

a
b c
d e f
g h i
j k
l

1
2 3
4 5 6
7 8 9
0 1
2

Upvotes: 1

Related Questions