Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Lisp

Idiom #187 Disjoint Set

Disjoint Sets hold elements that are partitioned into a number of disjoint (non-overlapping) sets.

(defstruct disjoint-set
  elements)

(defun make-disjoint-set (elements) 
  (make-disjoint-set :elements elements))

(defun partition (disjoint-set)
  (loop for element in (disjoint-set-elements disjoint-set) 
       collect 
        (let ((found (find element (mapcar #'first (rest disjoint-set)) 
                    :test #'equal)))
          (if found
              (acons element element found :test #'equal)
              (acons element element nil :test #'equal)))))
public class DisjointSetElement {
  private DisjointSetElement representative = this;

  public DisjointSetElement getRepresentative() {
    if (representative != this) {
      representative = representative.getRepresentative();
    }
    return representative;
  }

  public void union(DisjointSetElement other) {
    other.getRepresentative().representative = getRepresentative();
  }
}
  

The class is usually subclassed with each element holding information about that specific element, and information about the aggregated set. The aggregated information is only used on the representative node

New implementation...
< >
Shaftway