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

1 Answer

0 votes
function printPairsWithSpecificDifference($arr, $difference) { 
    $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) 
               echo $arr[$i] . " " . $arr[$j] . "\n";
    } 
} 
  
$arr = array(25, 16, 8, 12, 20, 17, 0, 4, 21, 26);
$difference = 4; 
    
printPairsWithSpecificDifference($arr, $difference); 




/*
run:

25 21
16 12
16 20
8 12
8 4
17 21
0 4

*/

 



answered Nov 30, 2021 by avibootz
...