我正在尝试设计一个函数来在迭代数组中的数字时执行减法。 第一个数字需要被删除并用于与剩余的数字相减。执行减法时,任何值都不应减少为负数。此外,如果遇到一个新值大于所保留的值,则保留的值将增加到较大值的数量。
我当前的代码:
function pairwiseDifference($array)
{
$n = count($array) - 1; // you can add the -1 here
$diff = 0;
$result = array();
for ($i = 0; $i < $n; $i++) {
// absolute difference between
// consecutive numbers
$diff = abs($array[$i] - $arry[$i + 1]);
echo $diff." ";
array_push($result, $diff); // use array_push() to add new items to an array
}
return $result; // return the result array
}
$array = [20,10,10,50];
// Percent of commisions are:
pairwiseDifference($array);
我的代码错误地打印了
10,0,40
,我需要以下值作为输出:0,0,30
。
一些额外的输入和所需的输出:
$input = [20, 10, 10, 50, 100, 25];
$output = [ 0, 0, 30, 50, 0];
$input = [80, 20, 30, 10, 50];
$output = [ 0, 0, 0, 0];
$input = [10, 40, 10, 50, 40];
$output = [ 30, 0, 10, 0];
由于数组的第一个元素是您的佣金,其他元素是父母的佣金,并且由于您似乎不想将您的佣金包含在结果数组中,因此您可以执行以下操作:
function pairwiseDifference($arry)
{
$n = count($arry);
$diff = 0;
$result = array();
$myComm = $arry[0]; // your commision
for ($i = 1; $i < $n; $i++)
{
$diff = 0; // set $diff to 0 as default
if($myComm < $arry[$i]) // if your commision < parent commision
$diff = $arry[$i] - $myComm;
echo $diff." ";
array_push($result, $diff);
}
return $result;
}
$arry = array(20,10,10,50);
echo "<br> Percent of commisions are: ";
$diffArray = pairwiseDifference($arry);
echo $diffArray[0]; // prints 0
echo $diffArray[1]; // prints 0
echo $diffArray[2]; // prinst 30
要根据您的代码调整逻辑,只需进行 3 处修改。
$max
变量并为其分配 $arry[0]
的值。0
,否则取差值。max()
函数再次计算新的最大值。片段:
<?php
function pairwiseDifference($arry)
{
$n = count($arry) - 1; // you can add the -1 here
$diff = 0;
$result = array();
$max = $arry[0]; // new addition
for ($i = 1; $i <= $n; $i++) // new modification <= n instead of < n
{
// absolute difference between
// consecutive numbers
$diff = $max < $arry[$i] ? $arry[$i] - $max : 0; // new modification
$max = max($max, $arry[$i]); // new modification
echo $diff." ";
array_push($result, $diff); // use array_push() to add new items to an array
}
return $result; // return the result array
}
$arry = array(20,10,10,50);
echo "<br> Percent of commisions are: ";
// this echos 10,0,40 and assigns whatever your function returns
// to the variable $diffArray
$diffArray = pairwiseDifference($arry);
为了简化将第一个值移出输入数组的步骤,请在将数组传递到自定义函数时解压该数组。
在函数签名中,将第一个值隔离为变量,然后将所有剩余值收集为数组。
循环缩短的数组,如果当前值大于要减去的量,则将当前值设置为两者之间的差,并将“减去”的量更新为原始值。否则将当前值减小为零。
代码:(演示)
function reduceCommissions(int $subtractBy, int ...$commissions): array
{
return array_map(
function($v) use (&$subtractBy) {
if ($v > $subtractBy) {
$difference = $v - $subtractBy;
$subtractBy = $v;
}
return $difference ?? 0;
},
$commissions
);
}
foreach ($tests as $test) {
var_export(reduceCommissions(...$test));
}
测试和输出:
$tests = [
[20,10,10,50], // [0, 0, 30]
[20,10,10,50,100,25], // [0, 0, 30, 50, 0]
[10,40,10,50,40] // [30, 0, 10, 0];
];