Given two sets of integers, write an algorithm to print the sum of overlapping elements in two sets.
Java Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; public class JavaExample { public static void findOverlappingElements(int [] setA, int [] setB){ System.out.println("Set 1: " + Arrays.toString(setA) + ", Set 2: " + Arrays.toString(setB)); Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i <setA.length ; i++) { int element = setA[i]; if(map.containsKey(element)) { int count = map.get(element); map.put(element, count+1); }else map.put(element, 1); } for (int i = 0; i <setB.length ; i++) { int element = setB[i]; if(map.containsKey(element)) { int count = map.get(element); map.put(element, count+1); }else map.put(element, 1); } //get sum of distinct elements int sum = 0; Set<Integer> set = map.keySet(); Iterator<Integer> iterator = set.iterator(); while (iterator.hasNext()){ int key = iterator.next(); int count = map.get(key); if(count==2) sum += key*count; } System.out.println("Sum of overlapping elements: " + sum); System.out.println("----------------------------------------"); } public static void main(String[] args) { int A[] = {2, 3, 1, 6}; int B[] = {4, 0, 6, 7}; findOverlappingElements(A, B); int C[] = {12, 13, 6, 10}; int D[] = {13, 10, 16, 15}; findOverlappingElements(C, D); } } |
Output:
1 2 3 4 5 6 7 | Set 1: [2, 3, 1, 6], Set 2: [4, 0, 6, 7] Sum of overlapping elements: 12 ---------------------------------------- Set 1: [12, 13, 6, 10], Set 2: [13, 10, 16, 15] Sum of overlapping elements: 46 |