#!/usr/bin/ruby

func consolidate() { [] }
func consolidate(this, *those) {
    gather {
        consolidate(those...).each { |that|
            if (this & that) { this |= that }
            else             { take that }
        }
        take this;
    }
}

enum |A="A", B, C, D, _E, F, G, H, I, _J, K|;

func format(ss) {
    ss.map{ '(' + .join(' ') + ')' }.join(' ')
}

var c = []

[
    [[A,B], [C,D]],
    [[A,B], [B,D]],
    [[A,B], [C,D], [D,B]],
    [[H,I,K], [A,B], [C,D], [D,B], [F,G,H]]
].each { |ss|
    var set = consolidate(ss...);
    c << set.map{ .sort };
    say (format(ss), "\n\t==> ", format(set));
}

assert_eq(c, [
    [["C", "D"], ["A", "B"]],
    [["A", "B", "D"]],
    [["A", "B", "C", "D"]],
    [["A", "B", "C", "D"], ["F", "G", "H", "I", "K"]]
]);