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