## Diagonal Difference

djgarrick + 101 comments I went for a non-array approach. Feedback much appreciated :)

`for(int j = 0; j < numInputs; j++){ for(int k = 0; k < numInputs; k++){ cin >> curInput; if(j == k){ leftD += curInput; } if(j+k == (numInputs-1)){ rightD += curInput; } } } ans = abs(leftD-rightD);`

dhananjay77 + 5 comments Interesting! (j+k == (numInputs-1)) is cool.

- WA
Waqas1 + 1 comment Yah Really interesting

- SS
CHODHARY + 2 comments # include

# include

# include

# include

# include

# include

# include

# include

# include

int main() { int a[100][100],n,c=0,d=0,i,j,sum=0; scanf("%d",&n); for(i=0;i for(i=0;i

- SS
CHODHARY + 0 comments int main() { int a[100][100],n,c=0,d=0,i,j,sum=0; scanf("%d",&n); for(i=0;i for(i=0;i

tarunapal9582 + 2 comments haha lol

- MM
mukul131999 + 0 comments kya karti rhte ha vellii

- SS
CHODHARY + 1 comment hat bosdiko

Zaf_Mohamed + 1 comment u dont need two loops for this, in one itself it can be done

- EF
fayazeleena + 2 comments how???

- IM
ishwor + 3 comments I still have one extra variable, which is unnecessary

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 totalSum=0; int j=n-1; for(int i=0;i<n;i++){ totalSum=a[i][i]-a[j][i]+totalSum; j--; } Console.WriteLine(Math.Abs(totalSum)); }

[DELETED] + 1 comment [deleted]- NR
rautnilesh8 + 1 comment What happen if input values are changed. I mean couple of more negative values in matrix

max_ragmo + 0 comments Does not affect the outcome, since it is the difference we are after, it is always a positive value

- GG
garg_gourav + 2 comments can be done in ((n-1)/2)+1 iteration

for (int i = 0; i < ((n - 1) / 2) + 1; i++) { total = ar[i][i] - ar[i][n - 1 - i] + ((i != n - 1 - i) ? ar[n - 1 - i][n - 1 - i] - ar[n - 1 - i][i] : 0) + total; }

- KS
kps_forums + 0 comments For a more readable format:

int squareDiffHalf(vector<vector<int>> matrix, int n) { int diff = 0; for (int i = 0; i < n/2; i++) { diff += (matrix[i][i] + matrix[n-i-1][n-i-1] - matrix[i][n-i-1] - matrix[n-i-1][i]); } return abs(diff); }

- GA
gilbertappiah9 + 0 comments Cannot read this. always go for a solutions others can read

- TG
gragest + 2 comments just in case you didnt know the for loop couldve been written like this for a cleaner look

for(int i = 0, j = n-1; i < n; i++, j--){ sum1 += a[i][i]; sum2 += a[j][i]; }

or as

for(int i = 0; i < n; i++){ sum1 += a[i][i]; sum2 += a[(n-1)-i][i]; }

- NR
nikhilraynade + 0 comments Great

- NO
niyaziozturkg + 0 comments Yes, it is a good thinking .. If anyone has read Herbert Schildt or Deitel's Java books would have recognized it.. my solution is the same.. some one else should be able to read it quickly..

`static int diagonalDifference(int[][] a) { int primeDi = 0, secondDi = 0; // could be improved to // int sum = 0; for (int i = 0 , j = a[0].length-1; i < a[0].length ; i++, j--) { primeDi += a[i][i] ; secondDi += a[i][j] ; // could be improved to // sum = a[i][i] - a[i][j] ; } return Math.abs(primeDi - secondDi); // could be improved to // return Math.abs(sum); }`

bit_tracer + 1 comment Complexity O(N). One Loop.

static int diagonalDifference(int[][] a) { int row=0; int column=a[0].length - 1; int solution = 0; for(int index=0;index<a.length;index++){ solution -= a[row][row] - a[row++][column--]; } return Math.abs(solution); }

- AP
anishpaul92 + 0 comments You will have to change to solution += a[row][row] - a[row++][column--];

- LM
larenmark + 0 comments wow thats creative!

- O
calgspv + 1 comment me too got the same logic

- MS
mohmmd_shoaib + 0 comments same here (Y)

Rjt5412 + 0 comments Yeah i never could have thought of that!!

- MV
pawin3210 + 1 comment How did you came up with the equation? I mean I'm new to programming and I need tips.

ckastam + 1 comment All you need is to have an understanding of mathematics and observe the mathematical expression. For example in the diagonal diffrence in a 3X3 array we have the following values for i,j respectively:

0,0 0,1 0,2

1,0 1,1 1,2

2,0 2,2 2,2

so the primary diagonal is 0,0 1,1 2,2 so it is obvious i=j the secondary diagonal is 2,0 1,1 0,2 so we can easily observe that i+j=n-1 (2+0=3-1, 1+1=2, 0+2=2)

rob_matthews + 0 comments nothing explained is obvious or as clear as could be.

- GP
rebelgiri + 0 comments me too same approch...

AllisonP + 2 comments Same, though my second if statement was the mathematically equivalent (i == (numInputs - j -1)).

- AA
amrita9 + 0 comments i=numinputs-j+1

- G
pumaboy_naik + 1 comment i didn't understand the above logic..help me out

- KC
xslipstream + 0 comments hey pumaboy, try writing out the matrix on paper and mark each box in matrix with row,col coordinates. To get the secondary diagonal, we need the values of [0,2] + [1,1] + [2,0]. Now think about how you would to these coordinates with a for loop. Think about how would you set up your if statements within your loop to capture these values?

isurudaulagala + 2 comments Yeah. You don't need to save the matrix into an array

- PK
santhosh_sunkari + 0 comments good

- AT
Turings_Ghost + 0 comments The problem explicitly states you start with an NxN array, so, per the rules expressed in the orientation, this would not be an acceptable answer. Not to say it doesn't give the same result, but in a real test, if they are seeing how you handle (a) the problem stated (i.e. changing the problem fundamentally = fail) and (b) how you used the constraints provided to solve the problem, this would be problematic.

ekahjhake + 2 comments I love this solution, neat and easy to understand... though for a beginner like me, array is our first choice. Thanks for sharing by the way.

pragu + 0 comments super

- AT
Turings_Ghost + 0 comments Unfortunately, while clever, it doesn't actually address the problem as given, which starts with the requirement of an NxN array.

Arvindcr7 + 2 comments surely your way of solution is quite good it saves a lot of space but if look 4 time it is not a cool solution if the number for matrix N is too high then for each entry there will be condition checking goes timely too much costly.

AllisonP + 6 comments This solution is actually asymptotically optimal for time as well as space, a certain amount of condition checking calculations would be required for ANY solution to this problem, and the overhead of storing data to an array is much higher than doing a simple condition check on data that is already loaded into computation registers while iterating through the loop (so your argument makes no sense). To use an array, which is what it seems like you are suggesting as a better solution, would just add several layers of inefficiency and could result in additional computation time as N becomes large due to the overhead involved in needlessly storing and reloading inputs that are not needed for calculation and are not needed beyond a single calculation. Using an array also becomes increasingly inefficient as N grows, because the more space you block out (the larger the array), the harder it is to find contiguous space in memory to store that array (so a lot of behind-the-scenes time consuming data shuffling takes place).

airais + 1 comment You are absolutely right. That being said, sometimes it may be better to write code that exhibits explicitly its logic, here "summing the elements of the diagonal of a square matrix" and for this purpose using a 2-D array could be better here I guess.

But yes, when it comes to performances, storing data used only once is clearly ineffective.

AllisonP + 2 comments In software engineering, algorithms get complex; part of being a good programmer is breaking down things into structured components and providing adequate documentation for your work, to both ensure you fully understand why what you did works and so others can better understand it during code review. Using an array for this is an incredibly sloppy thing to do, because there is no need for it and you would still need an algorithm to calculate the values in the array--you should not add layers of complexity to your code that have no benefit. The only reason to use an array for this type of thing would be if you knew there would be a future need to perform additional calculations on the same set of data. At my job, an attempt to use an array for something like this would be kicked back in a code review and never make it to release.

irvision_bsb + 1 comment IMHO, I would preffer saying "it depends", if I had to reuse this code for some reason,it would be written as a function or a method, in this case the array would be provided as a parameter, therefore storing it is not an option, it is mandatory.

Another scenario would be calculating the difference as part of the processing, as you've mentioned.

But I defenitely agree that to solve this specific problem you don't need to store the information.

GaborBartal + 0 comments Well, you don't need to use the array, only the diagonals, as the task is very specific. Building on the idea that we might need to use the array later feels like a cop-out to explain bad coding. If you'd need to use the array values, you would be given a different task, not this one.

- IM
ichidan + 1 comment My solution used an array as the default template code (C++) provided such. Looking at various discussions of solutions to HR problems, it seems as if we're encouraged to remove the template code and just write our own solution. I'm sure it's mentioned somewhere.

If the task is to demonstrate algorithm skills then developers should be encouraged to start fresh. If however, the task is to demonstrate ability to process/manipulate an array or STL vector, then the best way would be to upgrade the HR testing system to just provide an interface (with the main hidden elsewhere). This would also mean coders don't have to deal with string streams for every single test. e.g.

class Solution : public ISolution { private: int evaluate(const std::vector< std::vector<int> >& input) { // implement solution here // } };

// focus on the intended problem, no need to think and waste times with string streams, cout & cin.

Just my two cents.

GaborBartal + 0 comments codingbat.com works like that, you just write the function - saves the hassle of writing basic stuff. On the other hand for people learning a language here, it helps a lot for these basics to burn in their memories.

Tritonal + 1 comment I don't believe any condition checking is required. The elements required to perform the calculations are fixed and the index of a for-loop can be used to access the correct row values, notwithstanding using an array or not.

AllisonP + 1 comment The required condition check is the FOR condition; the algorithm checks the index of the current iteration in the FOR loop and performs an appropriate action (skip data, use in calculation, increment counter, end loop execution).

- HA
haideragha + 1 comment condition checking for FOR loop conditions is trivial because of compilers optimizations. OP has additional condition checking that is not optimal. And you clearly implied that it was necessary.

AllisonP + 0 comments Performing constant time operations

*n*times (the number of iterations of the loop) is, by definition, not trivial when discussing running time. The act of saving data to an array could be considered trivial, because it's an additional^{2}*O(1)*time operation within the loop.

- DA
drew_adorno + 8 comments You do not need to have any conditions to complete this problem.

`int main() { int n; int firstDiagonal=0; int secondDiagonal=0; cin >> n; int count=n-1; vector< vector<int> > a(n,vector<int>(n)); for(int a_i = 0;a_i < n;a_i++){ for(int a_j = 0;a_j < n;a_j++){ cin >> a[a_i][a_j]; } } for(int i=0; i<n; i++) { firstDiagonal+=a.at(i).at(i); secondDiagonal+=a.at(count).at(i); count--; } cout << abs(firstDiagnol-secondDiagnol); return 0; }`

Because the diagonal are always going to be positions we know when we have the size of the matrix.

- AP
thriggle + 2 comments You've actually got 3xN conditions, counting all your loops, but I like your thinking.

Here's my solution from JavaScript:

`var n = parseInt(readLine()); var suma = 0, sumb = 0; for(var i = 0; i < n; i++){ var line = readLine().split(' '); suma += Number(line[i]); sumb += Number(line[n-i-1]); } console.log(Math.abs(sumb-suma));`

- W
wei972008 + 0 comments [deleted] - JM
JocoMagic + 0 comments Hey there i'm pretty newbie and don't quite understand what the vectors are for and what they are doing, and if you could also explainwhat is going on with your third FOR statement i would appreciate it. Thanks in advance.

- PK
Puneet3821 + 3 comments no need to use extra for loop.

for(int a_i = 0;a_i < n;a_i++){ for(int a_j = 0;a_j < n;a_j++){ cin >> a[a_i][a_j]; } d1 = d1 + a[a_i][a_i]; d2 = d2 + a[a_i][n-1-a_i]; }

- H
- SD
sumit_dutta + 1 comment there is a segmentaion fault in your code.

ben_nxumalo + 0 comments $first = $second=0; $j = $n-1; for($i=0;$i<$n; $i++){ $first +=$a[$i][$i]; $second +=$a[$i][$j]; $j--; } $result= abs($first-$second); print abs($result);

- AT
Turings_Ghost + 0 comments Slightly cleaner and more readable:

`int diag1 = 0, diag2 = 0; for(int p = 0; p<n; p++) { diag1 += a[p][p]; diag2 += a[p][n - (p + 1)]; }`

bhargavisri + 0 comments Can you please explain me

firstDiagonal+=a.at(i).at(i); secondDiagonal+=a.at(count).at(i);gaganbaheti_it20 + 1 comment you will get an error. i tested your code and it's showing error

- JP
jesus_rpalos + 0 comments I had no problem running my code when I submitted.

- AT
Turings_Ghost + 0 comments Every "for" has a condition. If you mean no "if" or other explicit condition statements, sure.

ckastam + 0 comments that's in int main....not in the function....

- SM
suketmehtani + 0 comments [deleted] - P
pycraft114 + 0 comments this is so wrong answer . O(N^2) is way worse then O(N)

irvision_bsb + 0 comments AlissonP, this discussion of inefficiency due to storing useless information actually shouldn't be the focus here, please note that the problem statement says "Given a square matrix of size N x N, calculate the absolute difference between the sums of its diagonals.".

- PK
santhosh_sunkari + 0 comments good

- S
shk161 + 1 comment cool :) am noob coder! wasted 40 mins for this logic but finally happy.

Appatucker + 2 comments You are not wasting any time when you are coding. You will always learn something if it takes sometime and you finish it. :)

md_faisal + 0 comments absolutely right.....

- MK
manasveemittal + 0 comments explain this to facebook co-founders. They actually learnt how to feel cheated by the better croook.

forrest_A_K_I_N + 0 comments same!

Tritonal + 2 comments I performed similar logic on each row, but used a temporary array. Difference being one loop absent confusing for-loop nesting. Solution in C#.NET.

AllisonP + 0 comments Two nested loops is basic/introductory-level CS knowledge; the outer loop (i) is rows and the inner loop (j) is columns, so each element is located at the appropriate (i,j) location just as it would be in a graphical representation. This should not be "confusing".

- RP
ignacio_rafael + 2 comments I did the Math on the reading loop:

`var d1_v = 0; var d2_v = 0; 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); d1_v += a[a_i][a_i]; d2_v += a[a_i][(n - 1) - a_i]; } Console.WriteLine(Math.Abs(d1_v - d2_v));`

- JM
JocoMagic + 1 comment Hey there could you add an explanation as to what your code does, i would appreciate it. Thanks in advance.

- TB
Taylor40 + 0 comments Ill explain his approach as mine is the exact same. He first creates the 2 int to hold the sum of each diagonal (d1_v and d2_v), Then during the loop that was precoded to retrieve the lines and set the two dimensional array he is getting the values at each one of those rows that need to be added base on which row (a_i) the loop is on. If you look at my post you will see how this can be utilized without the two dimensional array.

- D
dass_2808 + 0 comments Nice work dude...!!

- PC
paulclift + 0 comments I used this as a basis for my c# submission as I was quite stumped.

misgevolution + 5 comments `int sum1=0,sum2=0; for(int i=0, k=size-1; i< size; i++){ for(int j=0; j< size; j++){ cin >> matrix[i][j]; if(i==j) sum1 += matrix[i][j]; } sum2 += matrix[i][k]; k -= 1; } cout << abs(sum1-sum2);`

Joxebus + 0 comments [deleted]souman1729 + 0 comments good thinking

jefflima + 2 comments Really nice one.

You can actually move up the k -= 1 into the outer loop next to the i++ as:

int sum1=0,sum2=0; for(int i=0, k=size-1; i< size; i++, k--){ for(int j=0; j< size; j++){ cin >> matrix[i][j]; if(i==j) sum1 += matrix[i][j]; } sum2 += matrix[i][k]; } cout << abs(sum1-sum2);

misgevolution + 0 comments Yes, thanks!

- DZ
Deeps79 + 1 comment what's the use of k here?? k=size-1...and k-- ? can Anyone help out..please

- AC
abhijith4514 + 0 comments Try writing a matrix in a paper and also give values to i,j,k as given above. You will understand why we need "k" much better that way, than just reading the code.

- VK
vinay666 + 0 comments good

lemueluhuru + 0 comments Nice. You can remove the conditional though, and complete this in one loop. Here is my solution in JavaScript.

`let primaryDiag = 0 let secondDiag = 0 let length = Matrix.length for (var i = 0, indexLength = length - 1; i < length; i++) { primaryDiag += Matrix[i][i] secondaryDiag += Matrix[i][indexLength] indexLength -= 1 } return Math.abs(primaryDiag - secondaryDiag)`

- S
sedhuramMV + 0 comments Nice logic :)

unovongalixor + 10 comments there's no need for nested for loops:

`matrix_size = int(input()) current_x_one = 0 current_x_two = matrix_size - 1 sum_one = 0 sum_two = 0 for line in range(matrix_size): input_string = input().split(" ") sum_one = sum_one + int(input_string[current_x_one]) sum_two = sum_two + int(input_string[current_x_two]) current_x_one += 1 current_x_two -= 1 print(abs(sum_one - sum_two))`

AllisonP + 4 comments The original poster is not writing a solution in Python, so pointing out functions and constructs available in a completely different language doesn't really add to this particular discussion IMO.

gabrielguelfi + 0 comments [deleted]gabrielguelfi + 0 comments Well, it added to me.

- PL
prlpzb + 0 comments [deleted] - M
msambitkumar1991 + 0 comments @allison it is all about algorithmic appraoch. A person can use any language to exhibit his/her ideas IMO.

sagemode + 1 comment In Python you are able to read and parse whole row easily, but it's not the same in java. The above solution is good for Java. Definitely Python is very powerful language!

AllisonP + 7 comments The same exact solution is easily accomplished in Java, but it still relies on saving unneeded values to an array which, as has already been pointed out, is actually a less optimal solution because it needlessly stores n^2 - 2n integers in arrays. Java equivalent of this python solution:

`public Solution(){ Scanner scan = new Scanner(System.in); int n = Integer.parseInt(scan.nextLine()); int sumOne = 0; int sumTwo = 0; for(int currentOne = 0, currentTwo = n - 1; currentOne < n; currentOne ++, currentTwo-- ){ String[] inputLine = scan.nextLine().split(" "); sumOne = sumOne + Integer.parseInt(inputLine[currentOne]); sumTwo = sumTwo + Integer.parseInt(inputLine[currentTwo]); } System.out.println(Math.abs(sumOne - sumTwo)); } public static void main(String[] args) { Solution s = new Solution(); }`

sagemode + 0 comments [deleted]sagemode + 4 comments I got your point, you are thinking in a very broad perspective applying it in a situation where memory is a constraint. Here it is not! Python takes 0.01 seconds to execute the above program unlike Java(0.1 - 0.29 seconds) that's why I stated it being very powerful. It is good to think in your terms where memory is getting wasted, but not here.

To your point "The same exact solution is easily accomplished in Java, but it still relies on saving unneeded values to an array which, as has already been pointed out, is actually a less optimal solution because it needlessly stores n^2 - 2n integers in arrays." Even in the below solution you are saving every input into curInput n^2 times which contradicts your point.

`for(int j = 0; j < numInputs; j++){ for(int k = 0; k < numInputs; k++){ cin >> curInput; if(j == k){ leftD += curInput; } if(j+k == (numInputs-1)){ rightD += curInput; } } }`

Yours Java equivalent solution to Python looks so hard to read.

Look at this Python solution:

`n = int(input().strip()) dSumLeft = 0 dSumRight = 0 for i in range(n): matrixRow = input().split() dSumLeft += int(matrixRow[i]) dSumRight += int(matrixRow[-(i + 1)])`

Simple and Powerful!

We need to learn and understand the balance required between performance and memory usage.

AllisonP + 1 comment I'd first like to note that this discussion thread is about a Java solution, and somebody just randomly posted a Python solution in it to demonstrate that the solution could be done without nesting loops (which is not an argument that anyone was making).

- Sure, Python is an easy to use and arguably powerful--I never said it wasn't; however, the use of dynamic language magic tends to make things slow, which one of the many reasons Python is generally referred to as a
**slow**language (though improvements have been made over the last 15 years). I'm really not sure what you are using to benchmark but, though Java has a high startup cost, it will almost always execute faster than Python. - As data sets get large, memory is
*always*a constraint; saving n^2 values to an array when only 2n are needed is not a scalable solution. - Please re-read my comment, as I did not contradict my own point at all. Saving a value from an input stream to a single register (which is an optimization any good compiler should make on this code) and then repeatedly overwriting it is not in any way the same as reading the n^2 values as a chunk, breaking the chunk down into n^2 components, storing n^2 values, and reloading and summing the 2n you actually need.
- The purpose of my comment was simply to point out that the same solution
*is*accomplishable in Java, because your comment incorrectly stated that Java couldn't read and break up a line the way that Python can and implied that is what makes Python a powerful tool. So I wrote a Java version of the Python poster's code, and pointed out why I still deem it not a good or scalable solution.

sagemode + 0 comments It's not quite right to say Java's performance is better than Python or viceversa, as one is better than other in different areas. I would like to repeat the following things again -

- It is good to think in your terms where memory is getting wasted, but "not here". I am a game developer and believe me I know exactly when one should be worrying about memory.
- I agree to the point of yours that saving a value into a single register is better than reading n^2 values as a chunk. But, is it arguably bad? Though we have better readability, and also it is easy to code. Again, believe me it is not!

- Sure, Python is an easy to use and arguably powerful--I never said it wasn't; however, the use of dynamic language magic tends to make things slow, which one of the many reasons Python is generally referred to as a
- MK
manasveemittal + 1 comment #!/bin/python import sys ''' n = int(raw_input().strip()) a = [] for a_i in xrange(n): a_temp = map(int,raw_input().strip().split(' ')) a.append(a_temp) z1,z2 = 0,0 for x1 in range(n): z1 += a[x1][x1] for x1 in range(n): z2 += a[x1][n-x1-1] print z1,z2 ''' n = int(input().strip()) dSumLeft = 0 dSumRight = 0 for i in range(n): matrixRow = input().split() dSumLeft += int(matrixRow[i]) dSumRight += int(matrixRow[-(i + 1)]) print dSumLeft-dSumRight

neither my code , nor yours is printing, please point the error

marttidumangeng + 3 comments try this

#!/bin/python import sys n = int(raw_input().strip()) dSumLeft = 0 dSumRight = 0 for i in range(n): matrixRow = map(int,raw_input().strip().split(' ')) dSumLeft += int(matrixRow[i]) dSumRight += int(matrixRow[n-i-1]) print abs(dSumLeft - dSumRight)

- CB
christopher_bir1 + 1 comment Here is a python 3 version below:

n = int(input().strip()) dSumLeft = 0 dSumRight = 0 for i in range(n): matrixRow = list(map(int,input().strip().split(' '))) dSumLeft += int(matrixRow[i]) dSumRight += int(matrixRow[n-i-1]) print(abs(dSumLeft - dSumRight))

bL4ck_r4bb1t + 0 comments [deleted]

- AS
ak311 + 0 comments plz explain

- T1
toaa_kama2354 + 0 comments Actually the above solution was not working for me, so I did the solution without taking the input as it was already described in the main function.

def diagonalDifference(a): # Complete this function sum1 = 0 sum2 = 0 for i in range(n): sum1 += int(a[i][i]) sum2 += int(a[i][n-i-1]) return abs(sum1 - sum2)

- CR
CodeRanger_121 + 0 comments hi i am a beginner in python can anyone explain me , how have they input 2D list in Python from the user ....

**for a_i in range(n): a_t = [int(a_temp) for a_temp in input().strip().split(' ')] a.append(a_t)** - VM
h150040481 + 0 comments That python code was brilliant

- SC
sandeep_ch41 + 1 comment hi Allison, below is my solution. Can you please provide your feedback.

`public static int diagonalDifference(int[][] numbers){ int pointerA = 0; int pointerB = numbers.length-1; int difference = 0; for(int i=0;i<numbers.length;i++){ difference -= numbers[i][pointerA]- numbers[i][pointerB]; pointerA++; pointerB--; } return Math.abs(difference); }`

- P
pgilescapone + 2 comments I like it. It was similar to mine in that there isn't a nested for loop iterating over multi dimensional array. My solution is unfortunately more pedantic and incurs looping twice.

//first diagonal int fd = 0; for (int i=0; i < n; i++) { fd += a[i][i]; } //second diagonal int sd = 0; int x = 0; int y = n-1; for (int j=0; j < n; j++) { sd += a[x++][y--]; } int answer = Math.abs(sd-fd); System.out.println(answer);

roky_zz + 0 comments very elegant solution, mine was similar:

for (var j = n-1, k = 0; j > -1; j--, k++ ) { diagonalB += arr[k][j]; }

- GK
148W1A1237 + 0 comments You are great

xisreal + 0 comments Great approach! Just a quick comment. You can take differences of left and right terms as you import each row. This computes a cumulative difference. There is no need to compute the sums first and then take differences. It's a bit simpler and, hopefully, faster ;)

rajarshi356 + 1 comment since i am a beginner will you please tell me what is the function of .split ?

sarinarw + 0 comments Let's say you have "1,2,3,hello" and you call .split(","). This will give you back an array of ["1", "2", "3", "hello"].

- BA
hertze_bogdan + 1 comment This is a solution where we go through the matrix only once, no arrays just check if we add the number to one of the diagonals or both.

public static void main(String[] args) { Scanner in = new Scanner(System.in); int N = in.nextInt(); int sumA =0, sumB = 0; int M = N*N; //counter for first diagonal int countA = N-N; // 0 -> N*N ; step N+1 // counte for second diagonal int countB = N-1; // N-1 -> N*N-N; step N-1 int countBLimit = M-1; // the last element is not for this diagonal for (int i = 0; i<M; i++) { int k = in.nextInt(); if (i == countA) { sumA += k; countA += N+1; } if (i == countB && countB < countBLimit) { sumB += k; countB += N-1; } } System.out.println(Math.abs(sumA-sumB)); }

rajarshi356 + 0 comments Thnx a lot

ArunkumarNR + 0 comments what is the need to parse the value to integer?

misgevolution + 1 comment There is no performance improvement in unfolding the 2d matrix in to 1d. Thats what you did here.

gabrielguelfi + 0 comments Well, he doesn't. Actually he does not care about "matrixes"(vectors of vectors), he simply looks in each simple vector by time, and pick two values (he already knows what values to pick, no verifying is needed), without relating one vector to another in a major matrix. Capisce?

It is a clever solution, dude!

gabrielguelfi + 0 comments [deleted]gabrielguelfi + 1 comment The brightness about this solution is that you don't have to verify each cell of the matrix to know if it is the value you need, cause you already know what cells to pick:

1 row: first and last; 2 row: second and last but one; 3 row: third and last but two;

and so on..

Clever!

misgevolution + 0 comments You are not paying attention to what input().split(" ") does. Yes string manipulation library could be highly optimzed that he might be saving some CPU cycles but I'm not sure if string tokenization is constant time operation. Definitely a cleaner and better solution though.

- MG
Ardillo + 1 comment It can be as simple as a line:

print(abs(sum([a[i][i] - a[i][n-i-1] for i in range(n)])))

- TR
themightyscot + 0 comments the square brackets around the difference/range part of the statement are not necessary.

- DP
an0o0nym + 0 comments Little bit tweaked example from above:

n = int(input()) diagonal1, diagonal2 = 0, 0 for i in range(n): row = input().split() diagonal1 += int(row[i]) diagonal2 += int(row[n-1-i]) print(abs(diagonal1-diagonal2))

- OM
OJ1010 + 0 comments This is great. I don't understand it much though... can anyone help?

reddyjahnavi + 0 comments Thanks a lot!!

- M
michelbetancour1 + 0 comments one liner python

print(abs(sum((lambda arr: int(arr[x]) - int(arr[len(arr) - x - 1]))(input().split()) for x in range(int(input())))))

other approach

n = int(input().strip()) result = 0 for x in range(n): arr = input().strip().split() result += int(arr[x]) - int(arr[n - x - 1]) print(abs(result))

- SN
sankaranarayana1 + 0 comments Great work rick.thanks for the idea of not using an array.....being a beginner all will think of using arrays which unnecessarilly will occupy some storage space.thanks once again for adding this code..

Draded + 1 comment `//I did it this way with one loop, but mine is less effective for(i=0;i<n*n;i++) { cin>>t; if(i%n==(i/n)%n){Lsum+=t;} if(i%n==n-1-(i/n)%n){Rsum+=t;} } cout<<abs(Lsum-Rsum);`

sagemode + 0 comments Though it's a single loop, still it's n*n loop. But that's a great formulae you have come up with, lot of thought process! But again I have read some where that modulos operation is very costly and try to avoid it. Thanks for sharing the solution.

- S
szhao13 + 1 comment Could someone help me understand what's happening with the line "cin >> curInput;"?

AllisonP + 1 comment It's reading in a value from

`cin`

and assigning it to a previously declared variable named`curInput`

. Each time the loop runs, it reads a variable value, assigns it to`curInput`

, processes it accordingly, and then loops again until the loop is finished. Because the value of`curInput`

is processed inside the loop and not needed again after processing, the value of`curInput`

just gets overwritten at each`cin >> curInput;`

.- S
szhao13 + 1 comment Ok, so it's not bitshifting? I thought the >> operator was for right bitshift, which is why I was so confused.

AllisonP + 2 comments You are correct in that it is also the bitshift operator. C and C++ also use them as IO operators with cin and cout. my understanding as far as the reason for it is that they wanted to make the IO operators analagous to unix IO redirection operators.

zarak + 0 comments Just a small aside - these IO operators were introduced in C++ - they don't exist in C.

- JR
coding_rj + 1 comment Yes, C++ allows classes to redefine the basic operators for their own purposes. This feature is usually referred to as "operator overloading": https://isocpp.org/wiki/faq/operator-overloading#op-ov-benefits

So, the handling of ">>" when used with the istream class is customized for each possible argument type: http://www.cplusplus.com/reference/istream/basic_istream/operator%3E%3E/

Many people think that operator overloading reduces the comprehensibility of code. Perhaps for this reason, the designers of Java decided against allowing operators to be re-defined. (Even so, Java natively overloads the "+" operator for java.lang.String to concatenate rather than perform a mathematical operation.)

- JD
j_delemosmartin + 0 comments sorry but i did not understand this properly. Can you explain it clearly please? Thank you in advance.

- VG
jainvinay143 + 0 comments awesome

- RY
ryerabaka + 1 comment Hi,

I have a question regarding this condition If our numInputs is an odd number

if(j == k) { leftD += curInput; }

at some point we will have a (j==k) in rightD as well and at this point the code will add to the leftD and rightD as well which would make the same to give you a wrong answer. Wont It?

Please forgive me. Noob Question if i havent seen something correctly.

AllisonP + 0 comments Because the numInputs is an odd number, the two diagonals will always cross at some point, resulting in one cell that is part of the sum of both diagonals. For a 3x3 matrix, the two diagonals are {(3,1), (2,2), (1,3)} and {(1,1), (2,2), (3,3)}; (2,2) is the center point and is part of both diagonals.

- LB
luisB + 0 comments it took me several minutes to understand your code im not that fast to analyse problems, what surprise me is how you decomposed the issue and found a solution within the loop, could you give me some tips about organize thoughts and everything to perform a better logic and not hardcoding things just like my solutions XD. thanks

surajkumarkumar + 0 comments whats about the number which is common in both digonal....

khuongduybui + 1 comment I don't even bother storing leftD and rightD.

if(j == k) { result += curInput; } if(j+k+1 == numInputs) { result -= curInput; } ans = abs(result);

nh2amine + 1 comment `result += ((j == k) - (j+k+1 == numInputs)) * curInput;`

khuongduybui + 0 comments Looks cool, but I don't like using bools for their binary values.

allano + 0 comments #!/bin/bash

read n;

sum=0;

for i in n ); do

read line;

sum=sum +

`echo`

`i -d " "`

- (`echo`

`((`

`i )) -d " "`

) ))done

echo $sum | sed -e 's/-//'`

gabrielguelfi + 1 comment Thx, dude! Nice approach! I did it before using array to store a literal matrix, but after reading it and the comments bellow, y'all convinced me to make it without storing data into arrays. Doing this way was a bit challenging using python, cause im not quite acquainted with the language, yet. But it worked. Thx!

And yes, it's better not to store data in arrays if you won't use it later.

Ah, your "(j+k == (numInputs-1)" condition is very nice. I was using "j == (numInputs-1)-k and k == (numInputs-1)-j". Your logical solution for this condition is much better than mine. Thanks for this learning too.

- MG
Ardillo + 0 comments Watch this:

print(abs(sum([a[i][i] - a[i][n-i-1] for i in range(n)])))

philipyoo + 1 comment Can someone explain what this line does?:

`cin >> curInput;`

- KK
hacker_vwdz2zxx + 0 comments It is reading input from a variable curInput. cin is the keyword of reading inputs in c++. >> is the operator to read values. Similarly cout<< curInput prints the output.

assembler07 + 0 comments A very clean solution, thank's for share ur algorithm ;)

fatboycodes + 0 comments Cool!

- RP
rishin458 + 1 comment I did something similar. :)

`int main(){ int n,*p,i,j,sum,k; scanf("%d",&n); p = (int *)calloc(n,sizeof(int)); for(i=0;i <= n*n - 1;i++) scanf("%d",&p[i]); j=0;k=n-1;sum=0; for(i=1;i<=n;i++) { sum += p[j]; sum -= p[k]; j += n+1; k += n-1; } printf("%d",abs(sum)); return 0;`

}

ashishdalal_yes + 0 comments its not working for me

- RR
ranju73 + 0 comments Super cool yar!!

magedmakar + 3 comments Why complexity of nested loop? This is how I solved it:

long sum1 = 0; long sum2 = 0;

`for (int i = 0; i < n ; i++) { sum1 += a[i][i]; sum2 += a[i][n - 1 - i]; } Console.WriteLine(Math.Abs(sum1 - sum2));`

shreeharshas + 0 comments This is what I did too! Takes O(n) time. Cheers!

ypahalajani + 1 comment Did the same in Java [ O(n) time complexity ]:

`for(int i=0; i<n; i++){ sum1+=arr[i][i]; sum2+=arr[i][n-1-i]; } System.out.println(Math.abs(sum1-sum2));`

- NM
15131A1284_meera + 1 comment why did keep + symbols infroont of sum1 and sum2..?

- SK
Shrazz_kotteda + 0 comments its like SUM=SUM+arr[i][i];

The + indicated that ^

HarshitAgrawal95 + 0 comments Amazing Man!! The solution is just AMAZING !!

shreeharshas + 0 comments I like this idea. I see that you don't need O(n^2) storage space but does it need O(n^2) time complexity? If so, can it be reduced?

- C
c4m170 + 0 comments Nice!

- JC
jaychaturvedi + 0 comments really cool approach

- PS
prateeksharmamay + 0 comments It means you are just considering the input values when the if conditions are true, otherwise all other values are discarded. Right ?

- PJ
prateekskit + 0 comments Thats Perfect !!

- SN
sankaranarayana1 + 0 comments superb sir hats off.......

m_amit + 0 comments nicely done

ZeroXLR + 0 comments Same here. Except since we are calculating the difference, I merely declared an int of 0 to hold the difference. In the first if conditional analogous to yours, I added to this int. In the second conditional, I subtracted from this int. My logic was, these early subtractions help keep the numbers small preventing early overflows.

- TL
tl255 + 0 comments This one is so cool and clear, thanks for sharing.

- SS
sachinsreedar92 + 0 comments public static int arraySum(int[][] array){ int total = 0;

`for (int row = 0; row < array.length; row++) { total += array[row][row]; } return total;`

}

- JG
jyoti273 + 0 comments Nice approach

- FM
fritzmatias + 0 comments You are using 2 variables "left and rigth" when you can use only one. wich one should be incremented and decremented.

dancinglightning + 0 comments Second loop (k) is not needed, index can be caluculated from array dimension and j

abhivasu + 0 comments this logic (j+k==n-1)is short and precise

- NP
pardesinilesh + 0 comments nice one!

- C[
Devbag + 0 comments Oh nice, I did this too in Javascript! I was afraid it wouldn't work because the pattern "seemed" to be that the x/y coordinates added up to be 1 less than N.

`var backSlash = 0; var forwardSlash = 0; for (var i = 0; i < n; i++) { for (var j = 0; j < n; j++) { if (i == j) { backSlash += a[i][j]; } if (i + j == n-1) { forwardSlash += a[i][j]; } } } console.log(Math.abs(backSlash - forwardSlash));`

- BS
bismeetsingh352 + 1 comment What is the curInput used for?

- C[
Devbag + 0 comments The current input :) cin >>> curInput.

- NB
balyan + 0 comments wow, awesome man you showed me a whole new way to look at this problem.

ankitcoder28 + 0 comments now it's look like a algorithm domain...

- AR
Abhimessi_fcb + 0 comments cool..bro

- HS
davidxavier378 + 0 comments it is the best solution of the question given and it is good even for large value of N;

sjmulder + 1 comment I did about the same, but using a single for loop and a single sum variable:

#include <stdio.h> #include <stdlib.h> int main(void) { int sz; scanf("%d", &sz); int sum = 0; for (int i = 0; i < sz*sz; i++) { int x; scanf("%d", &x); if (!(i % (sz+1))) sum += x; if (i > sz-2 && i < sz*sz-1 && !(i % (sz-1))) sum -= x; } printf("%d\n", abs(sum)); }

- AN
asadullonurulla1 + 0 comments thanks

- HJ
hirenjagani + 0 comments nice approch , solution is quite good

- LV
se61990 + 0 comments Cool !!!

- DS
DiegoS + 0 comments it was my condition for show an different example

if(a_i==(n-a_j-1))

koolkaju + 0 comments We can reduce the complexity by both loop at same time execute and no if condition like this:

`i think its better approach instead of using two if condition. for(int i = 0,j = n; i < n && j > 0; i++,j--){ diag1 += arr[i][i]; diag2 += arr[i][j]; }`

- SA
skhan75 + 0 comments this won't work for an odd square matrix like 3x3, 5x5, 7x7

- PF
paul_felkner + 1 comment Could you maybe explain the: "cin >> curInput;"? I know that >> is used for bitshifting, but that is about it. Eveen after research I still have no coue how your solution works.

Thanks in advance.

- JR
coding_rj + 1 comment - PF
paul_felkner + 0 comments Thank you very much for the quick reply :)

azar1019 + 0 comments Very intersting solution.

Silver_Shark + 0 comments i tried with this method but it is showing terminated due to timeout

- AP
abhishekp03 + 0 comments Great Dude! if(j+k == (numInputs-1))

sandip1805 + 1 comment if(j+k == (numInputs-1))

really instresting logic. how you find this?

- AP
abhishekp03 + 0 comments It is simple. The value of j and k is the left diagonal for a square matrix is always eaqual whereas for the right digonal, the sum of j and k is equal to the number of rows/column int the matrix.

- JJ
wogkr2618 + 0 comments How can I use like this code in Java

Sorry I'm a beginner haha

- CK
chetankh23 + 0 comments Great !!

imh1j4l + 0 comments great thinking :D

- PP
piyushrocks123 + 0 comments Interesting !!

- JD
j_delemosmartin + 0 comments sorry but i did not understand the "cin >> curInput" line :(

- A
arpit719 + 0 comments awesome bro !!

tonybui + 0 comments Haha without using array approach is very cool.

topeth + 0 comments Brilliant!

- R
rinu_budhbhatti + 0 comments what would be the numInputs here, example plz.

- AM
uyr_sust + 0 comments please explain it.

- S
stv_yang10 + 0 comments Cool answer! I couldn't figure out until i draw the total of x and y coordinate in paper. Total of right diagonal is always same!

- P
puneethts + 0 comments Two for loops expensive.. function solve(n, arr){ var primarySum = 0; var secondarySum = 0; arr.forEach(function(v, row){ primarySum+=v[row]; secondarySum+=v[n-row-1]; });

return Math.abs(primarySum - secondarySum); }

wdoering + 0 comments What does this do? If this is a bit shift, what is the purpose?

`cin >> curInput;`

- K
kachi_kinjal + 0 comments if(j+k == (numInputs-1)) You are awesome :)

- SS
CHODHARY + 0 comments # include

# include

# include

# include

# include

# include

# include

# include

# include

int main() { int a[100][100],n,c=0,d=0,i,j,sum=0; scanf("%d",&n); for(i=0;i for(i=0;i

- UG
gunjan_utsav + 0 comments you are good in math,certainly!

ben_nxumalo + 0 comments second=0; n-1; for(i<i++){ a[i]; a[j]; $j--; }

- S
samaiyar + 0 comments wow.. surely a thing to learn

nomadevproject + 0 comments nice approach!

- MH
hydragon + 0 comments that is more nicer way than the way i did it k == (size-1)-j

- RB
shanuraj1995 + 0 comments awesome logic dude

m0g + 0 comments Awful solution, it takes O(n^2) which is quadratic time, this does not scale. No idea why people are cheering this code.

VaibhavMagon + 0 comments Awesome!

- AS
akashsharma22441 + 0 comments It's Simply so brilliant!!!

cameronroe + 0 comments Aren't nested for loops a performance bottleneck? They perscribe to O(n^2) right? Isn't that unscalable?

- RM
rishikra5 + 0 comments why is there (numinputs-1) and not (numinputs+1)?

rachitex + 0 comments Explain j+k == (numInputs-1) ?? For every matrix element a

_{jk}. When j+k would be equal to numInputs+1, then and only then it is right Diagonal. For example, in matrix of three, every element with j+k=4 (where 4 is numInput 3 + 1). Kindly explain this to me.a

_{11}b_{12}c_{21}c_{22}Here 1+2 and 2+1 = 3.

hackaroo + 0 comments Did this in python

n = len(a) ans = 0 for i in xrange(n): ans+=a[i][i] - a[i][n-i-1] print abs(ans)

- JP
jesus_rpalos + 0 comments Mine followed a similar logic, but you don't actually have to use two for loops. You already know the relationship between j and k, so you can use just one for loop to increment j.

int rightD = 0; int leftD = 0; for(int i = 0; i < n; i++){ leftD += a[i][i]; rightD += a[i][n-i-1]; } System.out.println(Math.abs(leftD - rightD));

pbelasco + 1 comment Came to the same result, but ruby way. Just one loop

diag1=diag2=0 for i in (0...n) diag1 += a[i][i] diag2 += a[i][n-i-1] end puts (diag1-diag2).abs

patrickclery + 0 comments Crazy! I got the EXACT same. Important to note you have to pass

`n`

to the function.def diagonalDifference(a,n) # Complete this function x = y = 0 for i in (0...n) x += a[i][i] y += a[i][n-1-i] end puts (x-y).abs end

- DR
deep5_rana + 0 comments O(N)Solution -

l=0 p=0 for i in range(len(a)): l+= a[i][i] p+= a[i][len(a)-1-i]

print(abs(l-p))

- DY
DanYoo940 + 0 comments dang.... what.. is curInput, and cin and leftD, as I finished by myself I was very proud but realized, i dont know anything lol

- B
bikergila26 + 0 comments Any Kotlin guys here? I'm trying to use the same logic here, but seems like always getting Runtime Error all the time. Could somebody tell me what is wrong here?

fun main(args: Array<String>) { val numInputs = readLine()!!.toInt() var leftD = 0 var rightD = 0 for (j in 0..numInputs) { for (k in 0..numInputs) { val curInput = readLine()!!.toInt() if (j == k) { leftD += curInput } if (j+k == (numInputs - 1)) { rightD += curInput } } } println(Math.abs(leftD - rightD)) }

- EH
enriqhz + 0 comments Nice, this is a rigth algorithm.

- S
sohanmnit + 0 comments static int diagonalDifference(int[][] a) { int l=a.length; int d1=0; int d2=0; for(int i=0;i

thecerebration + 0 comments Really innovative!

- T
thanneeruvenu + 0 comments int x = 0; int y = 0; int index = a.length-1; for(int i=0; i } return Math.abs(x-y);

- BK
rlackswhd91 + 0 comments that's pretty cool that you calculate both in one go of for loops

- SC
samarththengine1 + 0 comments Very Creative....Great Work dude

- JT
betade + 0 comments Testing

Gamanoid + 13 comments My solution is to accumulate the mirrored difference in each row like so:

`N = int(input()) total = 0 for i in range(N): row = input().split() total += int(row[i])-int(row[-(i+1)]) print(abs(total))`

the only conversions are at two indeces per row regardless of size.

- D
darthfrazier + 0 comments Thats clever. I like this solution +1

arshdeepbakshi + 1 comment nice..but it should be raw_input().split() in line4 and not input().split()

Gamanoid + 0 comments I was using Python 3 :)

asepwhite + 2 comments cool, now the complexity is O(n);

theep0 + 0 comments Nope. Still n^2. With a much more work being done by splitting the string.

misgevolution + 0 comments Seems you forgot taking into account the split() operation.

SachitMNayak + 0 comments brilliant!

Tritonal + 0 comments This is what I was referring to in earlier comments. No if logic is required. This is similar to my solution.

- AK
Ugaga + 3 comments My version:

r1, r2 = 0, 0

for i in range(int(input())):

`T = list(map(int,input().split())) r1 += T[i] r2 += T[-i-1]`

print(abs(r1-r2))

Tritonal + 0 comments No if-then logic... Nice.

- BG
blessengeorge40 + 0 comments Thats a really good solution. Made a note of the indexing used for the second diagonal.

WallyAli + 0 comments i'm surprised this worked for you. it doesn't work.

`T[i]`

is not incremented properly. you are adding all the elements in`range(3)`

. if for example the input is`'11 2 4 4 5 6 10 8 -12'`

, you are`11 2 and 4`

instead of`11 5 and 8`

. same thing with`T[-i-1]`

.Also,

`T = list(map(int,input().split()))`

is inside the for loop. which means input has to be repeated in each iteration. you should move it outside the loop.

ericali + 0 comments I like this solution!

sagemode + 1 comment Hi Gamanoid! Can you please explain me how row[-(i+1)] is automatically evaluated to row[N - (i + 1)]? New to Python!

kashyapnadig + 0 comments In Python, negative list indices means you count backwards from the end of the list. [-1] refers to the last item and so on.

WallyAli + 0 comments This solution doesn't work. first,

`row = input().split()`

is inside the for loop. input has to be entered in each iteration. second,`int(row[i])-int(row[-(i+1)])`

is not properly incremented. you are not skipping to the next row.here is a solution that works (inspired by yours):

`N = int(input()) matrix = input().split( ) a = 0 b = -1 total = 0 for i in range(N): try: b -= N - 1 total += int(matrix[a]) - int(matrix[b]) a += N + 1 except IndexError: break print(abs(total))`

you need the

`exception`

or you will will get`indexError list index out of range`

.sadly, my solution still needs to be optimized. it runs in

`6.943235158920288 seconds`

darioshanghai + 0 comments Same solution I used :)

- YL
liuyushan + 0 comments This one is very nice

- JM
meerasiri38 + 0 comments result=[] a=int(input("Enter the no of rows")) b=int(input("Enter the no of cols")) c=[[int(input("enter the elements:"))for j in range(a)]for i in range(b)]

for i in range(a): for j in range(b): s=0 if i==j: print(sum(c[i][j])) s=(c[i][j]) #s += c[i][j] result.append(sum(s)) print(sum(s))

- HA
andepzaifggg + 0 comments what a fool and fucking guy you r!

karmasakshi + 2 comments I see people using nested loops to solve this. I think it is not necessary. Here's my JS code:

`var lr = rl = 0; for(var i = 0; i<n; i++){ lr += a[i][i]; rl += a[i][n-i-1]; } console.log(Math.abs(lr-rl));`

- DR
DCRussianDev + 0 comments Your solution assumes that the array is already available for you to reference. Other people have nested for loops as they need to create or read in the matrix from the input in order to access it. Other than that difference, your solution is similar to the others.

- DN
DhNaCse + 1 comment You can calculate the sum as you iterate as well.

var sum = 0; for(var i = 0; i<n; i++){ sum += a[i][i]; sum -= a[i][n-i-1]; } console.log(Math.abs(sum));

- J
jamesyu608 + 0 comments Similar to my version:

let sum = 0; for (let i = 0; i < n; i++) { sum += a[i][i] - a[i][n-1-i]; } console.log(sum >= 0 ? sum : sum * -1);

StefanK + 2 comments Simple Python, using the array a and size n given.

`primSum = 0 secSum = 0 #go through the rows for row in xrange(n): primSum += a[row][row] secSum += a[row][n - 1 - row] print abs(primSum - secSum)`

shreeharshas + 0 comments Same here. Implemented in C#.

`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 d1Sum = 0, d2Sum = 0; for(int i=0;i<n;i++){ d1Sum += a[i][i]; d2Sum += a[i][n-1-i]; } Console.WriteLine(Math.Abs(d1Sum - d2Sum)); }`

SErAphLi + 0 comments more simple

a = [list(map(int, input().split())) for _ in range(int(input()))] print(abs(sum([a[i][i]-a[i][-i-1] for i in range(len(a))])))

bimalkumar_p + 2 comments `int primDig=0; int secDig=0; for(int i=0; i < n; i++){ primDig+=a[i][i]; secDig+=a[i][n-1-i]; } System.out.println(Math.abs(primDig-secDig));`

bagzpain + 0 comments just like mine

magedmakar + 1 comment That's exactly how I solved it. Don't understand the need for the complexity of the nested loop.

- SD
subas113 + 1 comment 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> Diagonal1= a.Select((x) => x.ElementAt(value +1)); int total1 = 0, total2=0; foreach (var b in Diagonal1) { total1 += b; value++; } int value2 = a.Length; IEnumerable<int> ans = a.Select((x) => x.ElementAt(value2 - 1)); foreach (var b1 in ans) { total2 += b1; value2--; } Console.WriteLine(Math.Abs(total1 - total2)); }`

}

- EP
EugeniaPais + 0 comments This was my solution:

public static void Main(string[] args) { int n = Convert.ToInt32(Console.ReadLine()); int[][] a = new int[n][]; int result = 0; 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); } //Here is my code for (int i = 0; i < n; i++) { result += ((a[i][i]) - (a[i][n - 1 - i])); } Console.WriteLine(Math.Abs(result)); }

GrahamS + 2 comments Why does everyone seem to keep two different totals and then subtract them at the end? Isn't it easier to just have one running total?

long total = 0; for (int i = 0; i < n; i++) { total += a[i][i]; total -= a[i][(n-1)-i]; } cout << abs(total) << endl;

KMH92 + 0 comments The beauty of python:

d1 = sum([a[x][x] for x in range(n)]) d2 = sum([a[x][n-1-x] for x in range (n)]) print(abs(d1-d2))

- IR
imran3968 + 2 comments I have solve using java

public static void main(String[] args) {

`Scanner in = new Scanner(System.in); int n = in.nextInt(); int a[][] = new int[n][n]; int d1sum = 0; int d2sum = 0; for(int a_i=0; a_i < n; a_i++){ for(int a_j=0; a_j < n; a_j++){ a[a_i][a_j] = in.nextInt(); if(a_j == a_i){ d1sum += a[a_i][a_j]; } if(a_i == n-a_j-1){ d2sum += a[a_i][a_j]; } } } int diff = d1sum-d2sum; System.out.println(Math.abs(diff)); }`

- VN
ValleyNovy + 0 comments How did you get the second part of d2sum if(a_i == n-a_j-1)?

farhanfarooqui + 0 comments More simple. Without an array

public static void main(String[] args) { int pSum = 0, sSum = 0, N, input; Scanner in = new Scanner(System.in); N = in.nextInt(); for(int i = 0; i < N; i ++){ for(int j = 0; j < N; j++){ input = in.nextInt(); if(i == j){ pSum += input; } if(j == N-(i+1)){ sSum += input; } } } System.out.println(Math.abs(pSum-sSum)); }

iRonit + 4 comments Do you even require arrays for this question? I did it this way. Please comment if this is more efficient or not. Thank you. My Code:

//My Code

`int n, a, i; int ft,st; int f=0,s=0,sum=0; cin>>n; ft=1; st=n; for(i=1;i<=(n*n);i++) { cin>>a; if(i==ft) { f += a; ft += n+1; } if(i==st && st!=(n*n)) { s += a; st += n-1; } } sum = abs(f-s); cout<<sum;`

- PC
Dijit + 1 comment Nope, you don't need arrays.

iRonit + 1 comment Is this more efficient?

AllisonP + 1 comment An array would be less efficient as you would be needlessly processing the input multiple times (during the original read, writing to an array, processing the data in the array); because the data the problem requires you to process (the spaces falling within a diagonal) only needs to be processed once and follows a mathematical pattern, to use an array is inefficient as it results in extra processing cycles and a lot of unnecessary space blocked out (as well as unnecessary data stored) in your heap. It could also be argued that your use of multiplication (n * n) is inefficient (as opposed to using nested loops), because multiplication is a much more expensive process than addition. If you are thinking about efficiency in terms of asymptotic notation, there is no real difference in efficiency as array and loop solutions for this problem both have the same asymptotic complexity (O(n)). If you're looking to learn more, I recommend "Algorithms Sequential & Parallel: A Unified Approach" 2nd edition by Russ Miller. He was by far my favorite professor, and it provides a really good high level overview of efficiency (don't get overwhelmed by the Math proofs, you can just skip over them and read the theory).

Tritonal + 1 comment I say don't be too retentive about the so called efficiency. Yeah as purist programmers like to think a milosecond shaved is a huge deal, but with processing power, memory and disk space at a discount it is negiligble at best.

We aren't coding low-level compiler type stuff here. I suspect most of the folks on this site are coding in the business application space. So don't be too much of a purist. (LOL).

AllisonP + 0 comments I think its a waste of time to think about efficiency for something like this as well, but the OP wanted to understand efficiency better (hence the nitpicky breakdown) which is understandable as it's an important part of learning to write better code; however, it is important with problems like this to consider whether or not the solution is the best and most appropriately scalable. This is how people learn to program as engineers and not just as someone who has enough limited skill to slap on a short term bandaid solution without understanding the whole picture.

Sort 1580 Discussions, By:

Please Login in order to post a comment