Created
July 19, 2015 11:58
-
-
Save alexanderjamesking/1bda7e34dd0cbb50838c to your computer and use it in GitHub Desktop.
numbers - weighted quick union
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
; attempt 4 - using weighted quick union, always puts the smaller tree under the bigger tree to reduce depth | |
(def nodes (atom {})) | |
(def sizes (atom {})) | |
(defn find-root [i] | |
(let [v (get @nodes i)] | |
(loop [i v] | |
(if (= i v) | |
v | |
(recur v))))) | |
(defn values-not-nil? [x y] | |
(and (not (nil? x)) (not (nil? y)))) | |
(defn connected? [x y] | |
(let [n @nodes | |
xv (get n x) | |
yv (get n y)] | |
(and (values-not-nil? xv yv) (= xv yv)))) | |
(defn connect! [x y] | |
(let [n @nodes | |
xv (get n x) | |
yv (get n y)] | |
(when (values-not-nil? xv yv) | |
(let [sx (get @sizes x) | |
sy (get @sizes y)] | |
(if (> sx sy) | |
((swap! nodes assoc x yv) | |
(swap! sizes assoc x (+ sx sy))) | |
((swap! nodes assoc y xv) | |
(swap! sizes assoc y (+ sy sx)))))))) | |
(defn connect-roots! [x y] | |
(let [root-x (find-root x) | |
root-y (find-root y)] | |
(connect! root-y root-x))) | |
(defn roots-connected? [x y] | |
(let [root-x (find-root x) | |
root-y (find-root y)] | |
(connected? root-x root-y))) | |
(defn add-node-to-map! [x] | |
(swap! nodes assoc x x) | |
(swap! sizes assoc x 1)) | |
(defn add-node! [x] | |
(add-node-to-map! x) | |
(connect-roots! x (- x 1)) | |
(connect-roots! x (+ x 1)) | |
(roots-connected? 1 x)) |
Author
alexanderjamesking
commented
Jul 19, 2015
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment