Reputation:
I'm studying Java. And i wanted to make the code for checking a 2D array that returns if it is a magic square or not.
In order to do that, i had to write couple of different methods and one of them was for checking is all the sum of elements in each columns are equal. I could do for rows, but i got little bit confused vwhen i tried to do that for columns. And my friend said it's almost same with the method which check all row's sums are equal. My method for rows are below.
public static boolean rowSumsOK(int arr[][], int total) {
boolean a = false;
total = sumOneRow(arr);
int x=0; // this will be counted sum for each rows
for (int i=0; i<arr.length; i++){
for (int j=0; j<=arr.length; j++){
x = x + arr[i][j];
}
if(x != total){
a = false;
break;
}
else
a = true;
}
return a;
}
and he suggested to change in that method for doing it for columns is:
x = x + arr[j][i];
I'm still little bit confused about this. Can you explain me for this method or show me another way to do it guys?
Upvotes: 1
Views: 8311
Reputation: 13097
I would keep another array(columnTotal) that has the totalSum of the elements in column i. Then loop through the columns, one column at a time, and sum the rows in that column. Basically, it's the code for row summing, but with the inner and outer loops reversed. Try something like this:
int columnTotal[] = new int[array.length];
for(int column= 0; column< array.length; column++)
{
columnTotal[column] = 0;
for(int row= 0; row < array.length; row++)
{
columnTotal[column] += array[row][column];
}
}
Upvotes: 0
Reputation: 25950
public static boolean columnSumsOK ( int arr[][], int total )
{
for ( int j = 0; j < arr [ 0 ].length; j++ )
{
int sum = 0;
for ( int i = 0; i < arr.length; i++ )
sum = sum + arr [ i ] [ j ];
if ( sum != total )
return false;
}
return true;
}
Upvotes: 2