How to optimize this algorithm?

Posted by Bakhtiyor on Stack Overflow See other posts from Stack Overflow or by Bakhtiyor
Published on 2010-06-18T09:42:22Z Indexed on 2010/06/18 11:23 UTC
Read the original article Hit count: 490

Filed under:
|
|
|

I have two sets of arrays like this for example.

$Arr1['uid'][]='user 1'; $Arr1['weight'][]=1;
$Arr1['uid'][]='user 2'; $Arr1['weight'][]=10;
$Arr1['uid'][]='user 3'; $Arr1['weight'][]=5;

$Arr2['uid'][]='user 1'; $Arr2['weight'][]=3;
$Arr2['uid'][]='user 4'; $Arr2['weight'][]=20;
$Arr2['uid'][]='user 5'; $Arr2['weight'][]=15;
$Arr2['uid'][]='user 2'; $Arr2['weight'][]=2;

The size of two arrays could be different of course. $Arr1 has coefficient of 0.7 and $Arr2 has coefficient of 0.3. I need to calculate following formula

$result=$Arr1['weight'][$index]*$Arr1Coeff+$Arr2['weight'][$index]*$Arr2Coeff;

where $Arr1['uid']=$Arr2['uid']. So when $Arr1['uid'] doesn't exists in $Arr2 then we need to omit $Arr2 and vice versa.
And, here is an algorithm I am using now.

foreach($Arr1['uid'] as $index=>$arr1_uid){
    $pos=array_search($arr1_uid, $Arr2['uid']);
    if ($pos===false){
        $result=$Arr1['weight'][$index]*$Arr1Coeff;
        echo "<br>$arr1_uid has not found and RES=".$result;
    }else{
        $result=$Arr1['weight'][$index]*$Arr1Coeff+$Arr2['weight'][$pos]*$Arr2Coeff;
        echo "<br>$arr1_uid has found on $pos and RES=".$result;
    }
}

foreach($Arr2['uid'] as $index=>$arr2_uid){
    if (!in_array($arr2_uid, $Arr1['uid'])){
        $result=$Arr2['weight'][$index]*$Arr2Coeff;
        echo "<br>$arr2_uid has not found and RES=".$result;
    }else{
        echo "<br>$arr2_uid has found somewhere";
    }
}

The question is how can I optimize this algorithm? Can you offer other better solution for this problem?
Thank you.

© Stack Overflow or respective owner

Related posts about php

Related posts about algorithm