August 28, 2018

Random line from a text file

Introduction

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

Clojure code

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

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

Tags: Software Computer Clojure IO Functional