I'm new to Clojure and functional programming. I'd like to create a list of 100,000 keys in the format: XXXXX-XXXXX-XXXXX-XXXXX-XXXXX
I do something like this:
(defn get-key [chunk-size, key-length]
(apply str
(flatten
(interpose "-"
(partition chunk-size
(take key-length
(repeatedly #(rand-nth "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"))))))))
(defn dump-keys [n, chunk-size, key-length]
(with-open [wrt (io/writer "keys.txt")]
(doseq [i (range n)]
(.write wrt (str (get-key chunk-size key-length) "\n")))))
Which produces
KYFL0-7YO6J-30XMV-ZIGE7-MK009
MNQZH-K7L8I-35C0K-7DS7Q-OTZWI
MVB9D-GHME9-IMGCL-YPAKX-4YZVD
... etc
However, it takes around 5 seconds, which is comparatively long compared to a similar imperative-style algorithm.
What's considered an idiomatic (and quick) way to do what I'm trying to do?
To get maximum speed for this, I would suggest the following techniques:
(char-array 29)
aset
to set the character at each position in the arrayjava.util.Random
).charAt
, e.g. something like (.charAt "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" (int (Rand/r 36)))
dotimes
for your loop - this is generally faster than mapping / anything with sequencesIf you do all the above, you should get very efficient code, probably as fast as you could write it in pure Java.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With