Untitled

 avatar
unknown
java
3 years ago
1.7 kB
6
Indexable
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class DisjointSubsets {

    public Map<String, String> hashMap = new HashMap<>();
    public String find(String element) throws IllegalArgumentException {
        if (Arrays.stream(AL07.Network.values()).anyMatch(val -> val.name().equals(hashMap.get(element)))) {
            return hashMap.get(element);
        }
        // should throw IllegalArgumentException if any of elements is not present
        if (hashMap.get(element) == null) throw new IllegalArgumentException();

        return find(hashMap.get(element));
    }
    public void union(String element1, String element2) throws IllegalArgumentException {
        // should throw IllegalArgumentException if any of elements is not present
        var a = find(element1);
        if (a == null) throw  new IllegalArgumentException();
        if (Arrays.stream(AL07.Network.values()).anyMatch(val -> val.name().equals(element2))) {
            // In case we are tagging as friendly/unfriendly
            hashMap.put(element1, element2);
        } else {
            var b = find(element2);
            if (b == null) throw  new IllegalArgumentException();
            if (b.equals(AL07.Network.UNKNOWN.name())) {
                hashMap.put(element2, element1);
            } else {
                hashMap.put(element1, element2);
            }
        }
    }

    public void addSubset(String element) throws IllegalArgumentException {
        // should throw IllegalArgumentException if any of elements is not present
        if (hashMap.containsKey(element)) throw new IllegalArgumentException();

        hashMap.put(element, AL07.Network.UNKNOWN.name());
    }
}
Editor is loading...