How to print all distinct 4 elements from an array that have the same given sum in PHP

1 Answer

0 votes
function getDistinct4Elements($arr, $sum) {
    sort($arr);
    
    $size = count($arr);
    
    for ($i = 0; $i <= $size - 4; $i++) {
        for ($j = $i + 1; $j <= $size - 3; $j++) {
            $k = $sum - ($arr[$i] + $arr[$j]);
            $fromstart = $j + 1;
            $fromend = $size - 1;
            while ($fromstart < $fromend) {
                if ($arr[$fromstart] + $arr[$fromend] < $k) {
                    $fromstart++;
                }
                else if ($arr[$fromstart] + $arr[$fromend] > $k) {
                        $fromend--;
                    }
                    else {
                        echo strval($arr[$i]) . ", " . strval($arr[$j]) . ", ";
                        echo strval($arr[$fromstart]) . ", " . strval($arr[$fromend]),"\n";
                        $fromstart++;
                        $fromend--;
                    }
            }
        }
    }
}

$arr = array(4, 8, 1, 5, 9, 0, 3, 7);
        
$sum = 18;

getDistinct4Elements($arr, $sum);




/*
run:

0, 1, 8, 9
0, 3, 7, 8
0, 4, 5, 9
1, 3, 5, 9
1, 4, 5, 8

*/

 



answered Aug 20, 2022 by avibootz
...