Mercurial > coderloop
diff src/reverse_seq.clj @ 0:307a81e46071 tip
initial committ
author | Robert McIntyre <rlm@mit.edu> |
---|---|
date | Tue, 18 Oct 2011 01:17:49 -0700 |
parents | |
children |
line wrap: on
line diff
1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/src/reverse_seq.clj Tue Oct 18 01:17:49 2011 -0700 1.3 @@ -0,0 +1,43 @@ 1.4 +(ns coderloop.reverse-seq 1.5 + (:use [clojure.contrib 1.6 + [duck-streams :only [file-str read-lines]] 1.7 + [str-utils :only [re-split]]]) 1.8 + (:use rlm.shell-inspect) 1.9 + (:use [clojure [string :only [trim]]])) 1.10 + 1.11 +(def c (file-str "/home/r/coderloop-test/reversesequence-c.in")) 1.12 +(def a (file-str "/home/r/coderloop-test/reversesequence-a.in")) 1.13 +(def b (file-str "/home/r/coderloop-test/reversesequence-b.in")) 1.14 + 1.15 +(defn test-trace-map [] 1.16 + (= [:a :b :c :d :e] 1.17 + (trace-map {:a :b :d :e :c :d :b :c}))) 1.18 + 1.19 + 1.20 +(defn read-name-map 1.21 + "takes a file of pairs of names and returns a map from the first 1.22 + element in those pairs to the second element in the pairs." 1.23 + [#^java.io.File file] 1.24 + (let [pairs (map #(re-split #"\W+" (trim %)) (read-lines file))] 1.25 + (zipmap (map first pairs) (map second pairs)))) 1.26 + 1.27 +(defn start-linked-map 1.28 + "takes a map-representing-a-list and finds the beginning of that list" 1.29 + [m] 1.30 + (first (remove (set (vals m)) (keys m)))) 1.31 + 1.32 +(defn trace-map 1.33 + "chains through a map-representing-a-list, building a list along the way." 1.34 + [m] 1.35 + (loop [index (start-linked-map m) 1.36 + chain (vector index)] 1.37 + (let [new-index (get m index ::sentinel)] 1.38 + (if (= new-index ::sentinel) 1.39 + chain 1.40 + (recur new-index (conj chain new-index)))))) 1.41 + 1.42 + 1.43 + 1.44 +(if (command-line?) 1.45 + (dorun 1.46 + (map println (reverse (trace-map (read-name-map (file-str (first *command-line-args*))))))))