diff options
Diffstat (limited to 'union-find/quick-union.lisp')
| -rw-r--r-- | union-find/quick-union.lisp | 39 |
1 files changed, 21 insertions, 18 deletions
diff --git a/union-find/quick-union.lisp b/union-find/quick-union.lisp index 0db2846..648aba4 100644 --- a/union-find/quick-union.lisp +++ b/union-find/quick-union.lisp @@ -7,37 +7,40 @@ (in-package :com.lisp-algo.union-find) -;;; Base functions - -(defun qu-create-network (n) +(defclass quick-union () + ((nw-size + :initarg :network-size + :initform 10 + :accessor network-size) + (nw + :initarg nil + :accessor network))) + +(defmethod initialize-instance :after ((algo quick-union) &key) "Build a quick-find network using a dynamic vector" + (with-slots ((n nw-size) (nw nw)) algo (let ((nodes (make-array n :fill-pointer 0))) (dotimes (id n) (vector-push id nodes)) - nodes)) + (setf nw nodes)))) -(defun qu-find-root (network node) +(defun quick-union-find-root (network node) "Find the root of a sub-tree in the network." (do ((id node value) (value (elt network node) (elt network value))) ((= id value) id))) -(defun qu-union (network n1 n2) +(defmethod union ((algo quick-union) n1 n2) "Connect to sub-tree together. union represent the union operation on the Quick Union algorithm" + (with-slots ((network nw)) algo (let ((new-network (copy-seq network))) - (setf (elt new-network (qu-find-root new-network n1)) - (qu-find-root new-network n2)) - new-network)) - + (setf (elt new-network (quick-union-find-root new-network n1)) + (quick-union-find-root new-network n2)) + (setf network new-network)))) -;;; Macro definitions - -(defmacro qu-connected (network n1 n2) +(defmethod connected ((algo quick-union) n1 n2) "Return true if n1 and n2 are connected and nil otherwise. connection represent the find operation on the Quick Union algorithm" - `(= (qu-find-root ,network ,n1) (qu-find-root ,network ,n2))) - -(defmacro qu-nunion (network n1 n2) - "A destructive version of union_" - `(setf ,network (qu-union ,network ,n1 ,n2))) + (with-slots ((network nw)) algo + (= (quick-union-find-root network n1) (quick-union-find-root network n2)))) |
