How to count all distinct pairs from array with specific difference between them in PHP

1 Answer

0 votes
function countPairsWithSpecificDifference($arr, $difference) { 
    $count = 0; 
    $size = count($arr); 
      
    for ($i = 0; $i < $size; $i++) {  
        for ($j = $i + 1; $j < $size; $j++) 
            if ($arr[$i] - $arr[$j] == $difference or $arr[$j] - $arr[$i] == $difference) 
                $count++; 
    } 

    return $count; 
} 
  
$arr = array(25, 16, 8, 12, 20, 17, 0, 4, 21, 26);
$difference = 4; 
    
echo countPairsWithSpecificDifference($arr, $difference); 



/*
run:

7

*/

 



answered Nov 30, 2021 by avibootz
...