0

Write a program that passes in an array and will then output:

1) all pairs that sum up to 10. 2) all unique pairs that sum to 10, no duplicates. 3) all unique pairs that sum to 10, no duplicates or reverse pairs.

I have the bellow so far but it only prints the following:
(1, 9) (1, 9) (4, 6) (4, 6) (5, 5) (5, 5)

public class SumOfPairs { 

public void pairedElements(int arr[], int sum) 
{ 
    int low = 0; 
    int high = arr.length -1; 

    while (low < high) { 
        if (arr[low] + arr[high] == sum) { 
            System.out.println(" ("+ arr[low] + ", " + arr[high] + ")");
        } 
        if (arr[low] + arr[high] > sum) { 
            high--; 
        } 
        else { 
            low++; 
        } 
    } 
} 

public static void main(String[] args) 
{ 
    int arr[] = {1, 1, 2, 4, 4, 5, 5, 5, 6, 7, 9}; 
    Arrays.sort(arr); 

    SumOfPairs sp = new SumOfPairs(); 
    sp.pairedElements(arr, 10); 
} 
  • This isn't hard, you should try to do this by hand and figure out the exact steps you need to make this work. You have a very good set of test vectors there, but you should reduce it down to just two pairs that work and two that fail, to make the hand solution easier to work with. – markspace Apr 01 '20 at 20:18

2 Answers2

0

You can use nested for loops. In outer loop you can iterate from 0 up to the last but one. In inner loop you can iterate from outer index + 1 up to the last element. Something like this:

for(int i = 0; i < arr.length -1; i++){
   for(int j = i + 1; j < arr.length; j++){
      if(arr[i] + arr[j] == 10){
        //do something
      }
   }
}
nogalo
  • 66
  • 8
0

As stated above use a nested for loop to find your pairs. To find duplicates or Unique pairs i would store them in a list and check the list for instances of a value.

public void pairedElement(int [] arr, sum){
List<String> pairs = new ArrayList<>();

for(int x : arr){
   for(int y : arr){
     if(x + y == sum)
      pairs.add("(" + x + "," + y + ")");
   }
}
 //to print all of the values:
pairs.foreach(x -> System.out.println(x));

To print the unique/duplicate pairs only id recommend checking out this Specifically the second answer will give you an idea of how to get 2 collections, one containing the unique items from the entire list (pairs) and the other containing values that are duplicates in the original list.