如何在C#中浏览2D数组的每个对角线?

时间:2015-07-02 11:14:31

标签: c# for-loop multidimensional-array

我有一个int [5,6]类型的数组。 :

myArray[1,2]+ myArray[2,1]

我想将值相加,例如: myArray[1,3]+ myArray[2,2]+ myArray[3,1]a bb ccc dddd eeeee ffffff ggggggg

我怎样才能以这种方式完成它:

<?php 
    if(isset($_POST['submit'])){
        $to = "rightysahu@gmail.com";
        $from = $_POST['email'];
        $first_name = $_POST['first_name'];
        $message = $first_name . " " . " wrote the following:" . "\n\n" . $_POST['message'];
        $headers = "From:" . $from;
        mail($to,$subject,$message,$headers);
        echo "Mail Sent. Thank you " . $first_name . ", we will contact you shortly.";

        }
    ?>

..等等?

1 个答案:

答案 0 :(得分:1)

通用解决方案

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

用法示例

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

输出

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

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