0

I have an array [4,3,5,5,7,6] and I want to loop through the sorted one and subtract the highest value from the preceding value, then subtract the remainder from the value behind it and so on, then in the end, I need one final value that comes when the loop is completed. For example Above array will be sorted like

Array
(
    [0] => 3
    [1] => 4
    [2] => 5
    [3] => 5
    [4] => 6
    [5] => 7
)

Now I want to find the difference between arr[5] and arr[4], the result will be 1, then subtract the result from arr[3] and so on till the loop is completed This is what I tried but it doesn't seem to work

for ($i = count($a)-1; $i >0; $i--){
        echo $result = $a[$i] - $a[$i-1];
        echo "<br />";
        if($result > 0) {
            if($result > $a[$i-2]) {
                echo $result = $result - $a[$i-2];
            } else {

            }
        }
4
  • count the size of the array. use a for loop where you use a iterator that substracts each time of the loop, then you can point at your last key in the array that way Commented Aug 8, 2018 at 17:45
  • Can you show me a working example? See my edit, this is what I tried but doesn't seem to work Commented Aug 8, 2018 at 17:50
  • What would be the output using the example array in your question? What do you mean by "remainder"? Commented Aug 8, 2018 at 18:02
  • In the given array, output would be 0 like 7-6 = 1, 5-1 = 4, 5-4 = 1, 4-1 =3, 3-3 = 0 Commented Aug 8, 2018 at 18:09

5 Answers 5

1

I think there is a more simple and fast way to achieve this:

$array = [4, 3, 5, 5, 7, 6];
rsort($array);
$result = $array[0] - $array[1];
for($i = 2, $count = count($array); $i < $count; $i++){
    $result = $array[$i] - $result;
}
print($result);

output:

0
Sign up to request clarification or add additional context in comments.

Comments

0

Do you wish this way?

$a = [1,1,1,3,1,7];
$result = null;
for ($i = count($a)-1; $i >0; $i--){
  if($result == null)
      $result = $a[$i-1];
  echo $result = $a[$i] - $result;
  echo "<br />";
  if($result == 0) break;
}

Comments

0

My first answer was wrong, i see you need to discard 2 keys after the first substraction.

This does the job:

<?php
$array = [3,4,5,5,6,7];
$reverse = array_reverse($array);

if (count($reverse) > 1) {
    $first = $reverse[0] - $reverse[1];
} else {
     //code should stop
}

$result = $first;

for ($i = 2; $i < count($reverse); $i++)  {
    $result = $reverse[$i] - $result;
}

echo $result;

Ouputs 0, just as in your example. And of course this code still needs check to see if the key of the array does exist while iterating

2 Comments

don't sort the array first and then reverse it .It slows your code .you count the $reverse array twice why not count it once and store it in a variable?You don't need the variable $first ,use instead $result directly. you should also put your for loop in the if ...
The array is not sorted in this example. I know it would slow the code. Good point about the count though. The example was build for a demo nothing more.
0
$numbers = [4,3,5,5,7,6];
sort($numbers);
$numbers = array_reverse($numbers);
$first = array_shift($numbers);
$second = array_shift($numbers);
$result = array_reduce($numbers, function ($carry, $current_item) {
    return $current_item - $carry;
}, ($first - $second));
echo $result;

1 Comment

each time you use array_shift ,the array is re-indexed.This slow your code execution time.When you sort the array first and then reverse it you also slow your code execution time.Use instead rsort.
0

To get the expected output you are seeking you can use rsort to sort descending and start with the highest number. The first 2 elements are subtracted to get the starting value. Loop through the remainder to get your result.

Here's how you can achieve that:

$a = [4, 3, 5, 5, 7, 6]; // Your unsorted array

rsort($a); // Sort array by descending of largest to smallest

$result = $a[0] - $a[1]; // Initial subtraction of first two values

unset($a[0], $a[1]); // Remove from array so it won't loop through

foreach ($a as $_a) { // Loop through remainder and subtract difference
    $result = $_a - $result;
}

echo $result; // Show your result

Yields:

0

If you care about reindexing due to the unset you can simply add an extra line after that:

$a = array_values($a); // Reindexes array starting at 0 if you desire

2 Comments

you said array_slice but use array splice in your code...You could simply use a for loop because array splice or array_slice slows your code execution time ...
@Elementary Good catch. I was linking and grabbed the wrong one too quickly. I did attempt the for loop way in my earlier edits. I am used to using foreach and don't have to worry about counts. However your point about execution time with array_splice did shed some insight. Seems unset is a lot faster than the array_splice and I can keep my foreach so I'll update answer to reflect that. If the OP cares about reindex I'll state he can do an array_values at that point.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.