Union of All Intersecting Sets

前端 未结 5 610
花落未央
花落未央 2021-01-20 08:08

Given a list of objects with multiple attributes I need to find the list of sets created by a union of all intersecting subsets.

Specifically these are Person object

5条回答
  •  情深已故
    2021-01-20 08:38

    while (!people.isEmpty()) {
        Person first = people.get(0);
        people.remove(first);
        Set set = makeSet(first);
        for (Person person : people) {
            for (Person other : set) {
                if (person.isRelatedTo(other)) {
                    set.add(person);
                    people.remove(person);
                }
            }
        }
        sets.add(set);
    }
    for (Set a : sets) {
        for (Set b : sets.except(a)) {
            for (Person person : a)
                for (Person other : b) {
                    if (person.isRelatedTo(other)) {
                        a.addAll(b);
                        b.clear();
                        sets.remove(b);
                        break;
                    }
                }
        }
    }
    

提交回复
热议问题