package com.knecon.fforesight.service.layoutparser.processor.utils;

import java.util.HashMap;
import java.util.Map;

// simple implementation of a disjoint-set data structure
// https://en.wikipedia.org/wiki/Disjoint-set_data_structure
public class UnionFind<T> {

    Map<T, T> parents = new HashMap<>();
    Map<T, Integer> numberOfObjects = new HashMap<>();


    public T find(T node) {

        if (!parents.containsKey(node)) {
            parents.put(node, node);
            numberOfObjects.put(node, 1);
        }
        if (!node.equals(parents.get(node))) {
            parents.put(node, find(parents.get(node)));
        }
        return parents.get(node);
    }


    public void union(T node1, T node2) {

        T root1 = find(node1);
        T root2 = find(node2);

        if (!root1.equals(root2)) {
            if (numberOfObjects.getOrDefault(root1, 1) < numberOfObjects.getOrDefault(root2, 1)) {
                parents.put(root1, root2);
                numberOfObjects.put(root2, numberOfObjects.get(root2) + numberOfObjects.get(root1));
            } else {
                parents.put(root2, root1);
                numberOfObjects.put(root1, numberOfObjects.get(root1) + numberOfObjects.get(root2));
            }
        }
    }

}

