我有两组这样的数组,例如。
$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;
当然,两个阵列的大小可能不同。 $ Arr1 的系数为0.7, $ Arr2 的系数为0.3。我需要计算以下公式
$result=$Arr1['weight'][$index]*$Arr1Coeff+$Arr2['weight'][$index]*$Arr2Coeff;
其中$Arr1['uid']=$Arr2['uid']
。因此,当$Arr1['uid']
中不存在$Arr2
时,我们需要省略$Arr2
,反之亦然。
而且,这是我现在使用的算法。
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";
}
}
问题是如何优化此算法?你能为这个问题提供更好的解决方案吗?
谢谢。
答案 0 :(得分:3)
由于您整理数组的方式,您可以使用array_combine($keys, $values)使用$Arr1
中的键和来自{{$Arr2
的值将['uid']
和['weight']
汇集到关联数组中1}}。使用关联数组可以简化计算:
$combi1 = array_combine($Arr1['uid'], $Arr1['weight']);
$combi2 = array_combine($Arr2['uid'], $Arr2['weight']);
// loop through the keys from both arrays
foreach (array_keys($combi1+$combi2) as $uid) {
// use the value from $combi1, or 0 if it isn't set
$value1 = isset($combi1[$uid]) ? $combi1[$uid] : 0;
// use the value from $combi2, or 0 if it isn't set
$value2 = isset($combi2[$uid]) ? $combi2[$uid] : 0;
// calculate our final weight
$result = $value1 * $Arr1Coeff + $value2 * $Arr2Coeff;
echo "<br>$uid final weight: ".$result."\n";
}
您的代码:
user 1 has found on 0 and RES=1.6 user 2 has found on 3 and RES=7.6 user 3 has not found and RES=3.5 user 1 has found somewhere user 4 has not found and RES=6 user 5 has not found and RES=4.5 user 2 has found somewhere
我的代码:
user 1 final weight: 1.6 user 2 final weight: 7.6 user 3 final weight: 3.5 user 4 final weight: 6 user 5 final weight: 4.5
答案 1 :(得分:1)
如果您将用户用作数组键会更容易。像这样:
$Arr1['user 1'] => array('weight'=>1);
$Arr1['user 2'] => array('weight'=>10);
...
然后你可以使用array_diff_assoc和array_intersect_assoc来找出哪些元素在哪个元素中而不在另一个元素中。
答案 2 :(得分:0)
您可以在线性O(log(n))
O(n)
的{{1}}复杂性内容中阻止二进制搜索。但您必须先从此创建树或在array_search
中对此数组进行排序。
有关二进制搜索的更多信息,请访问:
答案 3 :(得分:-2)
首先,您应该将数组初始化为关联数组。计算会更容易。