Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automate sum in array

Tags:

arrays

loops

php

I will try to explain the problem that I have with this code.

This script works well to up to three persons ($numRows = 3).

$z=0;
$i=0;
$x=0;

do {
    $total[] = (
        ${'contaH'.$z}[$i+0]*$final[$x+0]+
        ${'contaH'.$z}[$i+1]*$final[$x+1]+
        ${'contaH'.$z}[$i+2]*$final[$x+2]
    );
    $z++;
} while ($z<$numRows); //3

But if I have only four persons ($numRows = 4), I need something like this:

$z=0;
$i=0;
$x=0;

do {
    $total[] = (
        ${'contaH'.$z}[$i+0]*$final[$x+0]+
        ${'contaH'.$z}[$i+1]*$final[$x+1]+
        ${'contaH'.$z}[$i+2]*$final[$x+2]+
        ${'contaH'.$z}[$i+3]*$final[$x+3]
        // if they are 5 persons ($numRows=5), here, should exists another row
    );
    $z++;
} while ($z<$numRows); //4

So the problem is to automate these changes in relation of $numRows.

Here is a demo of matrix algebra:

Enter image description here

The only thing that I want is put my code dynamically in a function of number of persons.

A   |  B |  C |  D
Person1
Person2
Person3
Person4
...

What can be different in my case is just the number of persons.

More information here.

like image 350
Daniel Avatar asked Nov 05 '22 12:11

Daniel


1 Answers

$z=0;
$i=0;
$x=0;
$numRows = 5;

do{
    $currentSum = 0;
    for($c = 0; $c < $numRows; $c++){
        $currentSum += (${'contaH'.$z}[$i+$c] * $final[$x+$c]);
    }
    $total[] = $currentSum;
    $z++;
}while($z < $numRows);
like image 128
dev-null-dweller Avatar answered Nov 09 '22 05:11

dev-null-dweller