Skip to content

Instantly share code, notes, and snippets.

@rmuslimov
Created April 21, 2016 21:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rmuslimov/5c9f7b09b8430f032966a44ad376fdc4 to your computer and use it in GitHub Desktop.
Save rmuslimov/5c9f7b09b8430f032966a44ad376fdc4 to your computer and use it in GitHub Desktop.
(ns shpn.core
(:gen-class)
(:require [clojure.java.io :as io]
[clojure.string :as s]))
(def input "nodes.txt")
(def findA "Node3")
(def findB "Node4")
(defn read-source
"Read source and build hashmap where keys is child and value is parent.
It's possible to have nil value that means not connected node"
[fname]
(let [rows (-> fname io/resource slurp (s/split #"\n"))
pairs (map #(s/split % #" ") rows)]
(zipmap (map first pairs) (map second pairs))))
(defn path-for
"Get path to root node."
[tree node]
(loop [acc [node] node node]
(let [parent (get tree node)]
(if-not parent
acc
(recur (conj acc parent) parent)))))
(defn -main
"Find lca for given tree and nodes."
[& args]
(let [tree (read-source input)
pathA (path-for tree findA)
pathB (path-for tree findB)]
(first (filter (set pathA) pathB))))
;; (-main)
;; Result: "Node1"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment