How to find the sum of two numbers in an array that match the input value

0

How to do this without having to make two loops.

Example method:

function getPairNumbers($array, $valor) {
  //aqui viria o método
} 
    
asked by anonymous 27.01.2017 / 18:45

1 answer

0

You can test each position, at the beginning and at the end of the array, and then test each position and increment as you find the desired value:

<?php
function getPairNumbers($numbers, $target)
{
    $result = array();
    sort($numbers);
    $high = count($numbers) - 1;

    for ($i = 0; $i < count($numbers);) {
        if ($numbers[$i] + $numbers[$high] == $target) {
            $result[0] = $numbers[$i];
            $result[1] = $numbers[$high];
            break;
        }

        if ($numbers[$i] + $numbers[$high] < $target) {
            $i++;
         }

        if ($numbers[$i] + $numbers[$high] > $target) {
            $high--;
        }

        if ($high <= $i) {
            return null;
        }
    }

    return $result;
}

$arr = getPairNumbers(array(1,4,5,15,30,25,20,0,13), 18);

print_r($arr);
    
27.01.2017 / 18:45