Write a Java program to find all pairs in random array whose sum is equal to given number using Set.

 

package testjava.javatest;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class SumOfPairs
{
    public static void main(String[] args)
    {    	
    	printPairs(getRandomArray(10), 7);
    	//printPairs(getRandomArray(8), 7);
    }
    
    public static void printPairs(int[] randomArray, int givenSum) 
    { 
    	System.out.println("Given Array: " + Arrays.toString(randomArray)); 
    	System.out.println("Given Sum : " + givenSum); 
    	System.out.println("Integer numbers, whose sum is equal to : " + givenSum); 
    	
    	Set<Integer> set = new HashSet<Integer>(randomArray.length); 
    	
    	for(int value : randomArray)
    	{ 
    		int target = givenSum - value; 
    		//System.out.println("Target: "+target+" Sum: "+givenSum+ " Value: "+value);	
    	
    		// if target number is not in set then add 
    		if(!set.contains(target))
    		{ 
    			set.add(value); 
    		}
    		else 
    		{ 
    			System.out.printf("(%d, %d) %n", value, target); 
    		}
    	}
    	System.out.println();
    }

    static int[] getRandomArray(int length)
    { 
    	int[] randoms = new int[length]; 
    	
    	for(int i=0; i<length; i++)
    	{ 
    		randoms[i] = (int) (Math.random() * 10); 
    	} 
    	return randoms; 
    }

}

Output:

Given Array: [6, 7, 5, 5, 9, 2, 4, 0, 7, 7]

Given Sum : 7

Integer numbers, whose sum is equal to : 7

(2, 5) 

(0, 7)