user2867504
user2867504

Reputation: 95

Dividing elements in arrays on specific numbers

I have N arrays like this (4 in example but number can be different)

k1 = [1,0,0,0,1,0,1]

k2 = [0,1,1,0,1,0,1]

k3 = [1,0,0,0,1,0,0]

k4 = [0,0,0,0,1,1,1]

I need to get the following arrays:

k1 = [0.5,0,0,0,0.25,0,0.33]

k2 = [0, 1,1,0,0.25,0,0.33]

k3 = [0.5,0,0,0,0.25,0,0]

k4 = [0, 0,0,0,0.25,1,0.33]

The idea is to divide each element on number of "1" occurrences for the same index in other arrays. So you always get 1 as sum of k1[i]+k2[i]+k3[i]+k4[i]+...kn[i]

Upvotes: 0

Views: 124

Answers (1)

Basto
Basto

Reputation: 216

You have to create a new array with the sum of all elements and then divide like this : there must be a "cleaner" way to do this but this works :

$k1 = [1,0,0,0,1,0,1];

$k2 = [0,1,1,0,1,0,1];

$k3 = [1,0,0,0,1,0,0];

$k4 = [0,0,0,0,1,1,1];

//we create an array with names of n array, i took 4 just to test it but it will works with n
$name=[];
for ($v = 1; $v <= 4; $v++) {
    $name[$v]="k".$v;
}

$sum=[0,0,0,0,0,0,0];

for ($k = 0; $k <= 6; $k++) {
    for ($j = 1; $j <= 4; $j++) {
        $sum[$k]=$sum[$k]+${$name[$j]}[$k];
    }
}

//and now we update 

for ($l = 0; $l <= 6; $l++) {
    if($sum[$l]!==0){
        for ($q = 1; $q <= 4; $q++) {       
            ${$name[$q]}[$l]=${$name[$q]}[$l]/$sum[$l];
        }
    }
}

//display to test
for ($m = 0; $m <= 6; $m++) {
    echo $k1[$m];
    echo " | ";
}

Upvotes: 1

Related Questions