typestar

temp_stats.clj in Clojure

Reports a week of high temperatures with a scaled bar per day and each day's distance from the mean.

;; Daily high temperatures for one week, in degrees Fahrenheit.
(def week
  [["Mon" 61] ["Tue" 68] ["Wed" 74] ["Thu" 79]
   ["Fri" 72] ["Sat" 65] ["Sun" 58]])

(def temps (map second week))
(def lo (apply min temps))
(def hi (apply max temps))
(def mean (/ (reduce + temps) (double (count temps))))

;; Each bar is scaled against the week's spread rather than against
;; zero, and the offset of 1 keeps the coolest day visible.
(defn bar [t]
  (let [span (max 1 (- hi lo))
        width (+ 1 (int (* 20 (/ (- t lo) (double span)))))]
    (apply str (repeat width \#))))

(println (format "%-5s %5s %-21s %5s" "DAY" "HIGH" "RANGE" "DIFF"))
(println (apply str (repeat 39 "-")))
(doseq [[day t] week]
  (println (format "%-5s %5d %-21s %+5.1f" day t (bar t) (- t mean))))
(println (apply str (repeat 39 "-")))
(println (format "%-5s %5d" "LOW" lo))
(println (format "%-5s %5d" "HIGH" hi))
(println (format "%-5s %5.1f" "MEAN" mean))
(println (format "%-5s %5d" "WARM" (count (filter #(> % mean) temps))))

How it works

  1. (apply min temps) and (apply max temps) bracket the week, and (/ (reduce + temps) (double (count temps))) gives the mean.
  2. (+ 1 (int (* 20 (/ (- t lo) (double span))))) scales a reading across the week's spread, and the added 1 keeps the coolest day visible.
  3. (format "%-5s %5d %-21s %+5.1f" day t (bar t) (- t mean)) prints the day, high, bar, and signed difference in aligned columns.

Keywords and builtins used here

The run, in numbers

Lines
26
Characters to type
981
Tokens
249
Three-star pace
80 tpm

At the three-star pace of 80 tokens a minute, this run takes about 187 seconds.

Type this snippet

Step 3 of 3 in Encore, step 27 of 27 in Language basics.

← Previous