I do not want to use a new data structure but the existing APIs in Java. Here's a solution. I am thinking if this can be made simpler. Input say {"1 2", "4 3", "5 5", "2 3"}
and output is [1, 2, 3, 4] [5]
static void formSet(String[] pairs) {
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);
Set<Integer> val1_set = null, val2_set = null;
for(Set<Integer> set : list){
if(set.contains(val1)) {
val1_set = set;
}
if(set.contains(val2)) {
val2_set = set;
}
}
if(val1_set == null && val2_set == null)
list.add(pairSet);
if(val1_set != null && val2_set == null)
val1_set.addAll(pairSet);
if(val1_set == null && val2_set != null)
val2_set.addAll(pairSet);
if(val1_set != null && val2_set != null){
list.remove(val2_set);
val1_set.addAll(val2_set);
}
}
for(Set<Integer> set : list){
System.out.println(set);
}
}
for(Set<Integer> set : list)
cycle. Alternative approach would be having a map from Integer to collection of Integers that it directly connects to, and then traverse recursively and collect into List of Sets (I'll see if I can come up with some code). \$\endgroup\$ – Coderino Javarino May 14 '17 at 10:17