Chonchol Mahmud - 1 year ago 195

PHP Question

I have a **N*N** Matrix.Now i want to know the diagonal difference of this Matrix.What will be the best approach of this solution?

I am trying with given approach:

Such as it is **3*3** Matrix say it is:

`11 15 85`

66 72 21

14 21 47

the diagonal simple formula will be:

`firstD= (11+72+47) = 130`

secondD = (85+72+14)= 171

diagonalDiff = |firstD - secondD| = |130-171| = 41

If I count every row such as first to find out

`firstD`

Can anyone tell me best approaches?

Answer Source

**Try this:**

```
$arr = array(
array(11, 15, 85),
array(66, 72, 21),
array(14, 21, 47),
);
$arrDiag = count($arr);
$firstD = 0;
$secondD = 0;
$i = 0;
for($j = 0; $j < $arrDiag; $j++){
$firstD += $arr[$i++][$j];
$secondD += $arr[$arrDiag - $i][$j];
}
echo abs($firstD - $secondD);//41
```