Align columns: Difference between revisions
Content added Content deleted
(→version 3: Note: This version adds boxes around columns of output.) |
(→{{header|Clojure}}: replaced code with shorter version) |
||
Line 366:
=={{header|Clojure}}==
<lang Clojure>
(def data "Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.")
(def table (map #(str/split #"\$" %) (str/split-lines data)))
(defn col-width [n table] (reduce max (map #(try (count (nth % n))
(catch Exception _ 0))
table)))
(defn add-padding
"if the string is too big turncate it, else return a string with padding"
[string width justification]
(if (>= (count string) width) (str/take width string)
(let [pad-len (int (- width (count string))) ;we don't want rationals
half-pad-len (int (/ pad-len 2))]
(defn
"get the width of each column, then generate a new table with propper padding for eath item"
([table justification]
(let [col-widths (map #(+ 2 (col-width % table)) (range (count(first table))))]
(map
(fn [row] (map #(add-padding %1 %2 justification) row col-widths))
table))))
(defn
[table]
(do (println)
(print (str/join "" (flatten (interleave table (repeat "\n")))))))
▲ (apply str (repeat cnt " ")))
▲ (case just
▲ :left (print (str wrd (spaces (inc diff))))
▲ :right (print (str (spaces diff) wrd " "))
▲ (print (str (spaces lhs) wrd (spaces (inc rhs)))))
▲(defn align-columns
(print-table (aligned-table table :center))
</lang>
|