Recently, I have been trying my hands on LINQ. So I've implemented the diagonal difference using Linq in Hackerrank. I know a similar question has been asked in python Diagonal Difference
Here is an excerpt of the problem Hackerrank -Diagonal Difference
Given a square matrix of size N X N , calculate the absolute difference between the sums of its diagonals.
Input Format
The first line contains a single integer, N . The next lines denote the matrix's rows, with each line containing space-separated integers describing the columns.
Output Format
Print the absolute difference between the two sums of the matrix's diagonals as a single integer.
Sample Input
3
11 2 4
4 5 6
10 8 -12
Sample Output
15
Explanation
The primary diagonal is:
11
5
-12
Sum across the primary diagonal: 11 + 5 - 12 = 4
The secondary diagonal is:
4
5
10
Sum across the secondary diagonal: 4 + 5 + 10 = 19
Difference: |4 - 19| = 15
My Code
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution {
static void Main(String[] args) {
int n = Convert.ToInt32(Console.ReadLine());
int[][] a = new int[n][];
for(int a_i = 0; a_i < n; a_i++){
string[] a_temp = Console.ReadLine().Split(' ');
a[a_i] = Array.ConvertAll(a_temp,Int32.Parse);
}
int value = -1;
IEnumerable<int> leftDiagonal= a.Select((x) => x.ElementAt(value +1));
int total1 = 0, total2=0;
foreach (var b in leftDiagonal)
{
total1 += b;
value++;
}
int value2 = a.Length;
IEnumerable<int> ans2 = a.Select((x) => x.ElementAt(value2 - 1));
foreach (var b1 in ans2)
{
total2 += b1;
value2--;
}
Console.WriteLine(Math.Abs(total1 - total2));
}
}
Final Statement
- I'm looking for improvements in terms of syntax, style, alternatives, and performance . I'm aware of the naming convention but some of these were the pre-defined structure in Hackerrank
- Using Linq this way is it an overkill for the small data?