Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
319 views
in Technique[技术] by (71.8m points)

data structures - Diagonal difference of a nested List C#

I'm trying to get from a function the absolute difference of a nested list. I have a fixed matrix, and I would like to get the result when is not fixed. At the moment I have a 3 x 3 matrix and this is what I've tried:

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

So, how can I adjust the function to get the absolute difference from a dynamic matrix? Thanks for the guidance and help!!

question from:https://stackoverflow.com/questions/65600741/diagonal-difference-of-a-nested-list-c-sharp

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Often, when we facing such problems we can query with a help of 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());

If you prefer good old for loop (please, note, that we want just one loop):

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

What's going on? We scan matrix (arr) line by line an sum the difference between left and right diagonal items:

6, 2, 3  -> 6 - 3 == 3 
1, 8, 2     8 - 8 == 0
3, 4, 7     7 - 3 == 4
            ----------
                     7 in total 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...