Lowest price ever! Learn Generative AI for 48% less!
Get my discount+ 1
Hackerrank -> Dashboard -> Algorithms -> Warmup -> Diagonal Difference
Think of your own solution for the following practice: 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 N lines denote the matrix's rows, with each line containing N space-separated integers describing the columns. Constraints: -100 <= elements <= 100 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
19 Answers
+ 16
+ 7
+ 7
@Nancy Liu you're right I didn't noticed that!🚨
+ 4
@Nancy Because the example provided was hard-coded and 11+ 99 == 33 + 77. 😉
+ 3
I see. Thanks for your info! I'm almost done and going to submit my attempt later! 😄
+ 2
@Nancy Liu nice challenge! I would appreciate if you can remove the extra 3 below Sample Input and align the matrix nicely as well. 😉
+ 2
@Zephyr Koo Thanks for your note, 3 is the input to indicate the size of the determinate~ I can align the matrix better:)
+ 2
Here's my C# implementation ✌
LINQ One-Liner〰
Math.Abs(
pDiagonalValues.Zip(
sDiagonalValues, (x, y) => x - y).Sum()
)
Note: I didn't follow the rules exactly and generate a random matrix on-the-fly. Enjoy!
https://code.sololearn.com/cjud461mpEe8/?ref=app
+ 2
C++ solution:
(This time I tried to define a parent Class Parent:P)
https://code.sololearn.com/c9wrXETKtc8E
+ 1
Python solution:
(I am now practicing to solve everything with Class)
https://code.sololearn.com/cyyhTFfq5zdo
+ 1
@Nancy Liu Glad to hear it! Thank you! 😄
+ 1
@Krishna Teja Yeluripati Thanks for contributing your JavaScript answer:) I am wondering why the output gives zero all the time.
+ 1
+ 1
@Zephyr Koo @ Krishna Teja Yeluripati I know the calculation~ But even I changed the matrix and run again, I still get zero as an output...
+ 1
3
3 6 4
6 8 9
3 5 9
@Tejaswa Rastogi this is my input... but it doesn't work...
+ 1
@Nancy do it like this:
3
3
6
4
6
8
9
3
5
9
0
@Zephyr Koo Nice coding style~
0
Hi @Tejaswa Rastogi I tried your code, the input cannot be passed well~
0
@Nancy, try giving 3(as an example) and give 9 elements for a 3*3 matrix. Enter your every input in a new line. It'll work fine. Better copy the code, and try into the terminal. I've not done input validation, so don't try to put wrong inputs! 😅