Created
November 12, 2015 11:10
-
-
Save bragboy/ad32f23eab6892dacb40 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package dsa.arrays; | |
| import java.util.HashSet; | |
| import java.util.Set; | |
| public class FindSumHashSet { | |
| public static void main(String a[]){ | |
| FindSumHashSet sumFinder = new FindSumHashSet(); | |
| sumFinder.begin(); | |
| } | |
| public void begin(){ | |
| int[] sampleArray = getRandomArray(20); | |
| int randomSum = sampleArray[15] + sampleArray[10]; | |
| System.out.print("ARRAY : "); | |
| for(int i:sampleArray){ | |
| System.out.print(i+" "); | |
| } | |
| System.out.println(); | |
| findPair(sampleArray,randomSum); | |
| } | |
| public void findPair(int[] sampleArray, int randomSum) { | |
| Set<Integer> sampleArraySet = new HashSet<Integer>(); | |
| for(int i=0;i<sampleArray.length;i++){ | |
| sampleArraySet.add(sampleArray[i]); | |
| int valueToFind = randomSum - sampleArray[i]; | |
| if(sampleArraySet.contains(valueToFind)){ | |
| System.out.println("SUM : "+randomSum); | |
| System.out.println("PAIR : "+valueToFind+","+sampleArray[i]); | |
| break; | |
| } | |
| } | |
| } | |
| private int[] getRandomArray(int size) { | |
| int[] randomArray = new int[size]; | |
| for(int i=0;i<size;i++){ | |
| randomArray[i] = (int)(Math.random()*10); | |
| } | |
| return randomArray; | |
| } | |
| } | |
| //SAMPLE OUTPUTS | |
| //ARRAY : 7 3 6 4 3 4 7 7 5 1 4 6 2 4 1 7 5 8 9 7 | |
| //SUM : 11 | |
| //PAIR : 7,4 | |
| //ARRAY : 0 2 9 6 0 7 6 5 1 7 9 0 7 1 2 4 4 3 9 0 | |
| //SUM : 13 | |
| //PAIR : 6,7 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment