John Davidson

php - Remove first element from array and implement conditional subtraction from all subsequent values in the array

0 comments
Message:


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];


My Answer:
= $n; $i++) {__ if ($i == 0) {__ $diff = array_shift($array);__ } else {__ $diff = max(0, $diff - $array[$i]);__ }__ $result[] = $diff;__ }__ return $result;_}_$array = [10, 5, 3, 8, 2];_print_r(pairwiseDifference($array));_// Output: [10, 5, 2, 0, 0]

Rate this post

5 of 5 based on 2927 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us