Try this:
<?php
$matriz = array(
array(1, 10, 3, 50),
array(1, 10, 3, 50),
array(1, 10, 3, 50),
array(1, 10, 3, 50),
array(1, 10, 3, 50)
);
$num_lines = count($matriz);
$num_elem_per_line = count($matriz[0]);
$maior = 0;
$maiorSoma = 0;
$soma = 0;
// Linha
for( $linha = 0; $linha <= ($num_elem_per_line-1); $linha++ ) {
// Coluna
for( $coluna = 0; $coluna <= ($num_lines-1); $coluna++ ) {
// Soma os elementos da linha
$soma += $matriz[$coluna][$linha];
}
// verifica se a soma atual é maior que a maior soma já registrada
if ( $soma > $maiorSoma ) {
$maior = $linha+1; // $linha é indice, logo, começa por 0, por isso +1
$maiorSoma = $soma;
}
// Reinicia a soma da soma para zero
$soma = 0;
}
echo "A linha de maior soma é: $maior <br>";
echo "A maior soma é: $maiorSoma";
?>
The algorithm will not accept that a next column is the largest sum if it has the same amount of elements, as in the following example:
$matriz = array(
array(1, 10, 3, 5, 10),
array(1, 10, 3, 5, 10),
array(1, 10, 3, 5, 10),
array(1, 10, 3, 5, 10),
array(1, 10, 3, 5, 10)
);
In this case, the algorithm will point out that the longest line is the second.
To change that, just put >=
there in the IF
Only works with matrices that have all columns with equal amount of elements
Does not work in the following example:
$matriz = array(
array(1, 10, 3, 50, 100),
array(1, 10, 3, 50),
array(1, 10, 3, 50),
array(1, 10, 3, 50),
array(1, 10, 3, 50)
);
You want to add up the column then, right? and not the line...
– JassRiver
Hello jassRiver, I tried to represent a square matrix in this code, in case I would sum the lines, as in the code would be the lines 1 1 1, 0 1 0 1, 0 1 1 1, 1 0 1 1.
– Bruno
I’m sorry, I didn’t remember the nomenclature used in the matrices.
– JassRiver