Diagonal Difference code in C#

Problem source: https://www.hackerrank.com/challenges/diagonal-difference

You are given a square matrix of size N×N. Calculate the absolute difference of the sums across the two main diagonals.

Input Format

The first line contains a single integer N. The next N lines contain N integers describing the matrix.

Constraints
1N100
100A[i]100

Output Format

Output a single integer equal to the absolute difference in the the sums across the diagonals.

Sample Input

3
11 2 4
4 5 6
10 8 -12

Sample Output

15

 

class Diagonal_Difference_Hackerrank
{
static void Main(string[] args)
{
int N = Convert.ToInt16(Console.ReadLine());
int[,] arr = new int[N, N];
string str = string.Empty;

for (int i = 0; i < N; ++i)
{
string[] strArr = Console.ReadLine().Split(‘ ‘);
for (int j = 0; j < strArr.Length; ++j)
{
arr[i, j] = Convert.ToInt16(strArr[j]);
}
}

int left = 0, right = N – 1, ldTotal = 0, rdTotal = 0;
while (N– > 0)
{
ldTotal += arr[left, left];
rdTotal += arr[left++, right–];
}

Console.WriteLine(Math.Abs(ldTotal – rdTotal));
}
}

 

Advertisements

One thought on “Diagonal Difference code in C#

  1. using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    class Solution {

    static void Main(String[] args) {
    // converts n to a usable integer (n dictates how many rows & columns there will be in the matrix)
    int n = Convert.ToInt32(Console.ReadLine());

    // Matrix 2d array creator (int[,] creates a multidimensional array)
    //new int[n,n] <- calls a new 2d array which is n "rows" by n "columns"
    int[,] matrix = new int[n, n];

    // Simple counter loop increments to n – the number of rows
    for(int numRows = 0; numRows < n; ++numRows)
    {
    // reads case and delineates it by spaces
    string[] strArr = Console.ReadLine().Split(' ');

    // counter loop increments to n – number of columns
    for (int numCols = 0; numCols 0)
    {
    // While it decrements n, it selects @ x,y = 2,2 / 1,1 / 0,0
    leftDiagTotal += matrix[left, left];
    // While it decrements n, it selects @ x,y = 0,2 / 1,1 / 2,0
    rightDiagTotal += matrix[left++, right–];
    }
    // Math.Abs
    int ans = (Math.Abs(leftDiagTotal – rightDiagTotal));
    Console.WriteLine(ans);
    }
    }

    // My own breakdown of the code above with research into every little thing

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s