【问题标题】:How can I go through every diagonal of a 2D array in C#?如何在 C# 中遍历二维数组的每个对角线?
【发布时间】:2015-09-19 21:24:57
【问题描述】:

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

   abcdef
   bcdefg
   cdefgh
   defghi
   efghij

我想将这些值相加,例如: myArray[1,2]+ myArray[2,1],或myArray[1,3]+ myArray[2,2]+ myArray[3,1]

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

a
bb
ccc
dddd
eeeee
ffffff
ggggggg

..等等?

【问题讨论】:

  • 你有char[,] 什么的?能否请您展示简短但完整的程序演示问题?
  • 您好,感谢您的回复。我编辑了更多细节的帖子。

标签: c# for-loop multidimensional-array


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多