嵌套列表 C# 的对角线差异

Jac*_*man 1 c# algorithm console-application nested-lists data-structures

我试图从函数中获取嵌套列表绝对差异。我有一个固定矩阵,我想得到何时不固定。目前我有一个3 x 3矩阵,这就是我尝试过的:result

List<List<int>> matrix = new List<List<int>> { 
    new List<int>() { 6, 2, 3 },
    new List<int>() { 1, 8, 2 },
    new List<int>() { 3, 4, 7 }
};

public static int diagonalDifference(List<List<int>> arr)
{
   int right = 0;
   int left = 0;
   int result = 0;

   for (int i = 0; i < arr.Count; i++)
   {
       for (int j = 0; j < arr.Count; j++)
       {
           right = arr[0][0] + arr[1][1] + arr[2][2];
           left = arr[2][0] + arr[1][1] + arr[0][2];
       }

       result = Math.Abs(right - left);  
   }

   return result;
}

//Output : 7
Run Code Online (Sandbox Code Playgroud)

那么,如何调整函数以获得动态矩阵的绝对差?感谢您的指导和帮助!!

Dmi*_*nko 7

通常,当我们遇到此类问题时,我们可以借助Linq进行查询

using System.Linq;

...

private static diagonalDifference(List<List<int>> arr) => Math.Abs(arr
  .Select((line, index) => line[index] - line[line.Count - 1 - index])
  .Sum());
Run Code Online (Sandbox Code Playgroud)

如果您更喜欢好的旧for循环(请注意,我们只需要一个循环):

private static diagonalDifference(List<List<int>> arr) {
  int result = 0;

  for (int i = 0; i < arr.Count; ++i) 
    result += arr[i][i] - arr[i][arr.Count - 1 - i];
 
  return Math.Abs(result); 
}
Run Code Online (Sandbox Code Playgroud)

这是怎么回事?我们逐行扫描矩阵 ( arr)line并求出左右对角线项之间的差值:

6, 2, 3  -> 6 - 3 == 3 
1, 8, 2     8 - 8 == 0
3, 4, 7     7 - 3 == 4
            ----------
                     7 in total 
Run Code Online (Sandbox Code Playgroud)