Diagonal Difference - HackerRank Solutions

 

Given a square matrix, calculate the absolute difference between the sums of its diagonals.

For example, the square matrix  is shown below:

1 2 3

4 5 6

9 8 9 

The left-to-right diagonal 1 + 5 + 9 = 15. The right to left diagonal 3 + 5 + 9 = 17. Their absolute difference is 2.

Function description

Complete the diagonalDifference  function in the editor below.

diagonalDifference takes the following parameter:

int arr[n][m]: an array of integers

Return

int: the absolute diagonal difference

Input Format

The first line contains a single integer, , the number of rows and columns in the square matrix .
Each of the next  lines describes a row, , and consists of  space-separated integers .

Output Format

Return the absolute difference between the sums of the matrix's two 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

 

In Java

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;



class Result {
  public static int diagonalDifference(List> arr) {
    int size = arr.size();
    int sum1 = 0;
    int sum2 = 0;
    for (int i = 0; i < size; i++) {
      for (int j = 0; j < size; j++) {
        if (i == j) {
          sum1 += arr.get(i).get(j);
        }
        if(i+j == size - 1){
          sum2 += arr.get(i).get(j);
        }
      }
    }
    return Math.abs(sum1-sum2);
  }
}



public class Solution {
    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        int n = Integer.parseInt(bufferedReader.readLine().trim());

        List> arr = new ArrayList<>();

        IntStream.range(0, n).forEach(i -> {
            try {
                arr.add(
                    Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" "))
                        .map(Integer::parseInt)
                        .collect(toList())
                );
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        });

        int result = Result.diagonalDifference(arr);

        bufferedWriter.write(String.valueOf(result));
        bufferedWriter.newLine();

        bufferedReader.close();
        bufferedWriter.close();
    }
}


In Python 

import math
import os
import random
import re
import sys



def diagonalDifference(arr):
  sum1 = 0
  sum2 = 0
  size = len(arr)
  for i, column in enumerate(arr):
    print(i, column)
    for j, value in enumerate(column):
      print(j, value)
      if i==j:
        sum1 += arr[i][j]
      if i+j == size - 1:
        sum2 += arr[i][j]
        
  return abs(sum1-sum2)



if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    n = int(input().strip())

    arr = []

    for _ in range(n):
        arr.append(list(map(int, input().rstrip().split())))

    result = diagonalDifference(arr)

    fptr.write(str(result) + '\n')

    fptr.close()

Comments

Popular posts from this blog

Pagination in PHP

File upload using JavaScript with validation (Apply validation on frontend side)