Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find number of distinct pairs of numbers whose sum is equal to some 'K' - PHP

Tags:

arrays

php

Given an array, I would like to display the count of distinct pairs of elements whose sum is equal to K - I've written code as below, but I am unable to put array_diff to good use :\

<?PHP
function numberOfPairs($a, $k) {
    $cnt = 0;
    for($i=0; $i<count($a); $i++){
        for($j=$i; $j<count($a); $j++){
            if($a[$i]+$a[$j] == $k){
                $arrRes[$i][0] = $a[$i];
                $arrRes[$i][1] = $a[$j];
                $cnt++;
            }
        }
    }
    sort($arrRes);
    //print $cnt;
    $d = $cnt;
    for($i=0; $i<count($arrRes); $i++){
        for($j=0; $j<count($arrRes); $j++){
            $diff = array_diff($arrRes[$i], $arrRes[$j]);
            if($diff == null)
                $d += 1;
        }
    }
    print $d;
}

$a = [6,6,3,9,3,5,1];
$k = 12;
numberOfPairs($a, $k);
?>

Here, the output arrays with sum equal to 12 are, i.e, the result of $arrRes is -

[0] => Array ( [0] => 3 [1] => 9 ) 
[1] => Array ( [0] => 6 [1] => 6 ) 
[2] => Array ( [0] => 6 [1] => 6 ) 
[3] => Array ( [0] => 9 [1] => 3 )

The count is 4, but the count should be 2, as (6,6) and (3,9) are the only distinct pairs.

like image 706
Prashanth kumar Avatar asked Jan 27 '26 15:01

Prashanth kumar


1 Answers

You can simplify your solution, by using fact that arrays in php are hashmaps:

function numberOfPairs($a, $k) {
    $used=[];
    for ($i=0; $i<count($a); $i++)
        for ($j=$i+1; $j<count($a); $j++) {
            $v1 = min($a[$i], $a[$j]);
            $v2 = max($a[$i], $a[$j]);
            if ($k == $v1+$v2)
                $used[$v1.'_'.$v2] = true;
        }
    return count($used);
}

$a = [6,6,3,9,3,5,1];
$k = 12;
echo numberOfPairs($a, $k);
like image 120
Iłya Bursov Avatar answered Jan 29 '26 03:01

Iłya Bursov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!