我有一个total_sum
变量(例如20.00)和一个数组,它并不完全等于变量的组合,total_sum
但非常接近:(array = [array(8=>1.49), array(1=>8.1)]
数组可以有更多值)索引是一个乘数键值:(8*1.49 + 1*8.1) = 20.02 != total_sum
。我需要找到将数组值提高到等于的算法total_sum
。数组的键不能更改,只能更改值。值仅需保留两位小数(价格/货币)
因此,此示例数组的结果将是:array(8*1.49 + 1*8.8)
[8.1更改为8.8,所以total_sum
现在= 20.00]
有人知道这样的问题,或者这个问题有名字吗?
因此,在过去一个小时中,我对此颇有兴趣:D。这是结果。希望这是您所期望的。从评论中我了解到您只希望具有双精度值。该函数将循环遍历,直到匹配双精度值。注意:可能会有更好的方法,但这是我想到的第一个方法。
function correction( $total, $input = array(), &$correction = null, $index = 0 ){
if( count( $input ) < $index ){
return;
}
$total_sum = 0;
foreach( $input as $multiplier => $value ){
$total_sum += $multiplier * $value;
}
$remains = 0;
$i = 0;
foreach( $input as $multiplier => $value ){
if( $i !== $index ){
$remains += $multiplier * $value;
}
$i++;
}
$rest = $total - $remains;
reset( $input );
$current_key = 0;
for( $i = 0; $i < $index; $i++ ){
next( $input );
}
$current_key = key( $input );
if( $current_key !== null ){
$value = $rest / $current_key;
$precision = strlen( $value ) - strpos( $value, '.' ) - 1;
if( $precision > 2 ){
$index++;
correction( $total, $input, $correction, $index );
} else {
$correction = array(
'index' => $current_key,
'value' => $value,
);
}
}
}
一些样本数据:
$total = 20;
$input = array(
8 => 1.49,
1 => 8.1,
);
correction( $total, $input, $correction );
echo '<pre>'; print_r( $correction ); echo '</pre>';
结果:
Array
(
[index] => 1
[value] => 8.08
)
另一个示例:
$total = 20;
$input = array(
8 => 1.49,
1 => 8.1,
3 => 2.1,
);
结果:
Array
(
[index] => 1
[value] => 1.78
)
这:
public static function correction( $total, $input = array(), &$correction = null, $index = 0 ){
if( count( $input ) < $index ){
return;
}
$total_sum = 0;
foreach( $input as $data ){
// if input is coming from user then
// you may want to check if indexes are set
$total_sum += $data['multiplier'] * $data['value'];
}
$remains = 0;
$i = 0;
foreach( $input as $data ){
if( $i !== $index ){
// same check here
$remains += $data['multiplier'] * $data['value'];
}
$i++;
}
$rest = $total - $remains;
$value = isset( $input[ $index ]['multiplier'] ) && $input[ $index ]['multiplier'] > 0 ?
$rest / $input[ $index ]['multiplier'] : 0;
$precision = strlen( $value ) - strpos( $value, '.' ) - 1;
if( $precision > 2 ){
$index++;
self::correction( $total, $input, $correction, $index );
} else {
$correction = array(
'index' => $index,
'value' => $value,
);
}
}
$total = 68;
$input = array(
array(
'multiplier' => 1,
'value' => 1.2,
),
array(
'multiplier' => 8,
'value' => 5,
),
);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句