Say I have a list of pair of elements like (1, 2) (3, 4) where no duplicates are present and for a pair (p, q) p != q. How to form a set from this elements using simple code (I do not intend to use a data structure like disjoint set and unions but java library APIs - unless the code can be written in a simple fashion). Example: (1, 2) (2, 4) (5, 6) (4, 7) (3, 5) should output: {1, 2, 4, 7} and {3, 5, 6}
List<Set<Integer>> list = new ArrayList<>();
for(String s : pairs){
String[] values = s.split(" ");
Integer val1 = Integer.parseInt(values[0]);
Integer val2 = Integer.parseInt(values[1]);
Set<Integer> pairSet = new HashSet<>();
pairSet.add(val1);
pairSet.add(val2);
boolean exists = false;
for(Set<Integer> set : list){
if(set.contains(val1) || set.contains(val2)) {
set.addAll(pairSet);
exists = true;
break;
}
}
if(!exists)
list.add(pairSet);
}
This is a naive approach which is incorrect. If I get a sequence (1 2) (3 4) and (2 3) then the output becomes {1, 2, 3} and {3, 4}.
This happens because the list of sets gets created like this: {1, 2} and then {3, 4} then when the pair (2 3) comes, it DOES NOT merge the 2 sets.
I can write a code to check the first value is present in any set say S1 and then same for the other value say S2 and then merge:
//loop -> s1 = find val1
//loop -> s2 = find val2
if s1 != null and s2 != null //merge s1 and s2
if(s1 == null && s2 != null) //add val1 and val2 to s2
if(s1 != null && s2 == null) //add val1 and val2 to s1
if(both null) create a new set of val1 and val2
Too many loops and conditions. Any simpler solution?
I am posting a solution. If someone can make this code simpler it would be great. TIA
here's a link to codereview: https://codereview.stackexchange.com/questions/163301/forming-a-set-from-a-pair-of-numbers