view 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 source
1 (ns coderloop.reverse-seq
2 (:use [clojure.contrib
3 [duck-streams :only [file-str read-lines]]
4 [str-utils :only [re-split]]])
5 (:use rlm.shell-inspect)
6 (:use [clojure [string :only [trim]]]))
8 (def c (file-str "/home/r/coderloop-test/reversesequence-c.in"))
9 (def a (file-str "/home/r/coderloop-test/reversesequence-a.in"))
10 (def b (file-str "/home/r/coderloop-test/reversesequence-b.in"))
12 (defn test-trace-map []
13 (= [:a :b :c :d :e]
14 (trace-map {:a :b :d :e :c :d :b :c})))
17 (defn read-name-map
18 "takes a file of pairs of names and returns a map from the first
19 element in those pairs to the second element in the pairs."
20 [#^java.io.File file]
21 (let [pairs (map #(re-split #"\W+" (trim %)) (read-lines file))]
22 (zipmap (map first pairs) (map second pairs))))
24 (defn start-linked-map
25 "takes a map-representing-a-list and finds the beginning of that list"
26 [m]
27 (first (remove (set (vals m)) (keys m))))
29 (defn trace-map
30 "chains through a map-representing-a-list, building a list along the way."
31 [m]
32 (loop [index (start-linked-map m)
33 chain (vector index)]
34 (let [new-index (get m index ::sentinel)]
35 (if (= new-index ::sentinel)
36 chain
37 (recur new-index (conj chain new-index))))))
41 (if (command-line?)
42 (dorun
43 (map println (reverse (trace-map (read-name-map (file-str (first *command-line-args*))))))))