Chonchol Mahmud - 7 months ago 104
PHP Question

# How to calculate Diagonal difference in PHP?

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`
(First row's first value + Sec row's Sec value + Third row's third value+..).This is my thinking.
Can anyone tell me best approaches?

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
``````
Source (Stackoverflow)