Random line from a text file

About getting a random line from a text file in Clojure.

Clojure code

1(time (let [path "/usr/share/dict/american-english-insane"
2            cnt (with-open [rdr (clojure.java.io/reader path)]
3                  (count (line-seq rdr)))
4            idx (int (rand cnt))
5            word (with-open [rdr (clojure.java.io/reader path)]
6                   (nth (line-seq rdr) idx))]
7        (println (str "Word #" idx ": " word " (from " cnt " words)."))))

Word #371611: kneecappings (from 650722 words). "Elapsed time: 201.590254 msecs"

Posts in this Series