I am trying to design a function to perform subtraction while iterating over the numbers in an array. The first number needs to be removed and used for subtraction with the remaining numbers. Upon performing subtraction, no value should be reduced to a negative number. Additionally, if a new value is encountered which is greater than the value being preserved, the preserved value will be increased to the amount of the greater value.
My current code:
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);
My code incorrectly prints 10,0,40
, and I need the following values as output: 0,0,30
.
Some additional inputs and desired outputs:
$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];
Since your first element of the array is your commission and the others are the the commissions of parents, and since it seems that you don't want to include your commission in the result array, you can do something like this:
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