Site Search:

Union Find Demo

Back>



>cat UnionFindDemo.java 
import java.util.*;
import java.io.*;
public class UnionFindDemo {
    public static String[] names = {"John", "Ben", "Miller", "Shao", "Yohi", "Eva", "Keith", 
        "Mooshy", "Dave", "Yin", "Charlse", "Emma"};
    public static String[][] friends = {{"John", "Ben"}, {"John", "Miller"},  
        {"Yohi", "Mooshy"}, {"Eva", "Ben"}};
    
    private static Map<String, Integer> unions = new HashMap<>();
    
    public void union(String name1, String name2) {
        int v = unions.get(name1).intValue();
        for(String name : unions.keySet()) {
            if(unions.get(name).intValue() == v) {
                unions.put(name, unions.get(name2));
            }
        }
    }
    
    public boolean isConnected(String name1, String name2) {
        if(name1 == null || name2 == null || unions.get(name1.trim()) == null || unions.get(name2.trim()) == null) {
            return false;
        }
        return unions.get(name1.trim()).intValue() == unions.get(name2.trim()).intValue();
    }
    
    public static void main(String...args) throws IOException {
        for(int i = 0; i < names.length; i++) {
            unions.put(names[i], i);
        }
        
        UnionFindDemo uf = new UnionFindDemo();
        
        for(int i = 0; i < friends.length; i++) {
            uf.union(friends[i][0], friends[i][1]);
        }
        
        
        
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String input = in.readLine();
        //name, name
        String[] pairs = input.split(",");
        System.out.println(unions);
        System.out.println(uf.isConnected(pairs[0], pairs[1]));
    }

}

>
>javac UnionFindDemo.java 
>java UnionFindDemo
John, Ben
{Eva=2, Mooshy=7, Keith=6, Shao=3, Miller=2, John=2, Ben=2, Dave=8, Yohi=7, Charlse=10, Emma=11, Yin=9}
true
>Mooshy, Miller
-bash: Mooshy,: command not found
>java UnionFindDemo
Mooshy, Miller
{Eva=2, Mooshy=7, Keith=6, Shao=3, Miller=2, John=2, Ben=2, Dave=8, Yohi=7, Charlse=10, Emma=11, Yin=9}
false
>