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

1 Answer

0 votes
public class MyClass {
    static void printPairsWithSpecificDifference(int arr[], int difference) { 
        int size = arr.length; 
  
        for (int i = 0; i < size; i++) { 
            for (int j = i + 1; j < size; j++) {
                if (arr[i] - arr[j] == difference || arr[j] - arr[i] == difference) {
                    System.out.println(arr[i] + " " + arr[j]);
                }
            }
        } 
    } 
    public static void main(String args[]) {
        int arr[] = { 25, 16, 8, 12, 20, 17, 0, 4, 21, 26 }; 
        int 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
edited Nov 30, 2021 by avibootz
...