Created
April 21, 2016 21:16
-
-
Save rmuslimov/5c9f7b09b8430f032966a44ad376fdc4 to your computer and use it in GitHub Desktop.
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
(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