Sum line in matrix

Asked

Viewed 126 times

-2

I implemented this code to sum line by row of the matrix and tell which row has the highest sum, but the output is blank, in which case the sum would be line 1 (1+1+1+1) line 2 (0+1+0+1) and so on. someone can help me?

  <?php
  $matriz = array
  (
   array(1, 0, 0, 1),
   array(1, 1, 1, 0),
   array(1, 0, 1, 1),
   array(1, 1, 1, 1)
 );
 $sum = 0;
 $no = 0;
 foreach ($matriz as $array){
    if(($sum += $array[$no])>$sum+=$array[$no+1]){
        echo "a linha de maior soma é =  $array[no]";
    }
 }
?>


 
  • You want to add up the column then, right? and not the line...

  • 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.

  • I’m sorry, I didn’t remember the nomenclature used in the matrices.

1 answer

2


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)
);
  • thanks friend.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.