Diagonal Difference Solution in Java | HackerRank | Diagonal Difference HackerRank Solution
Diagonal Difference Solution in Java
Diagonal Difference HackerRank Solution in Java
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 = . The right to left diagonal = . Their absolute difference is .
Function description
Complete the function in the editor below. It must return an integer representing the absolute diagonal difference.
diagonalDifference takes the following parameter:
- arr: an array of integers .
Input Format
The first line contains a single integer, , the number of rows and columns in the matrix .
Each of the next lines describes a row, , and consists of space-separated integers .
Constraints
Output Format
Print 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
Note: |x| is the absolute value of x
https://www.hackerrank.com/challenges/diagonal-difference/problem
Diagonal Difference HackerRank Solution in Java
Diagonal Difference Solution 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<List<Integer>> arr) { // Write your code here int main=0,secondary=0; for(int i=0;i<arr.size();i++){ for(int j=0;j<arr.size();j++){ if(i==j){ main=main+(int)(arr.get(i).get(j)); System.out.println(main); } if(i+j==arr.size()-1) { secondary+=(int)(arr.get(i).get(j)); System.out.println(secondary); } } } if((main-secondary)<0) return (main-secondary)*-1; else return (main-secondary); } } 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<List<Integer>> 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(); } }
0 Comments