gpt4 book ai didi

php - 如何优化这个算法?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:51:09 27 4
gpt4 key购买 nike

例如,我有两组这样的数组。

$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";
}
}

问题是如何优化这个算法?你能为这个问题提供其他更好的解决方案吗?
谢谢。

最佳答案

由于数组的组织方式,您可以使用 array_combine($keys, $values)使用来自 ['uid'] 的键和来自 ['weight'] 的值将 $Arr1$Arr2 组装成关联数组。使用关联数组大大简化了计算:

$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.6user 2 has found on 3 and RES=7.6user 3 has not found and RES=3.5user 1 has found somewhereuser 4 has not found and RES=6user 5 has not found and RES=4.5user 2 has found somewhere

我的代码:

user 1 final weight: 1.6user 2 final weight: 7.6user 3 final weight: 3.5user 4 final weight: 6user 5 final weight: 4.5

关于php - 如何优化这个算法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3068586/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com