Skip to content

Instantly share code, notes, and snippets.

@paultopia
Last active January 16, 2017 08:45
Show Gist options
  • Select an option

  • Save paultopia/8882df6ca35ae91e7e36f4b27d7361ef to your computer and use it in GitHub Desktop.

Select an option

Save paultopia/8882df6ca35ae91e7e36f4b27d7361ef to your computer and use it in GitHub Desktop.
Depth-first search in clojurescript
#!/usr/bin/env planck
;; note: I haven't included any lein or boot tooling since there are no
;; dependencies. the easiest way to run is to use planck on osx, as a script.
;; can also be easily adapted to normal clojure or have some tooling added if you want to
;; run it and don't have a mac
(ns dfs.core
"depth-first search of tree. Makes a few assumptions for simplification purposes:
1. tree is directed graph
2. stored in map in form
{:node [:child-node1 :child-node2 etc.]}.
3. Assumes no cycles
4. searches from 'right' qua end of node vector.
5. Assumes that root node is known (search won't begin at nonexistent node)
6. Based on 5, represents singleton tree as empty map. (so (dfs {} :a :a) returns a match ")
(defn push [stack new-items]
(if (= new-items nil)
stack
(into [] (concat stack new-items))))
(defn inner-dfs [stack tree start-node target-node]
(let [children (get tree start-node)
new-stack (push stack children)]
(cond
(= start-node target-node) target-node
(empty? new-stack) nil
:else
(recur (pop new-stack) tree (peek new-stack) target-node))))
(def dfs (partial inner-dfs []))
;; example:
(def example-tree {:a [:b :c] :b [:d :e :f] :c [:g] :g [:h]})
(println (dfs example-tree :a :g))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment