Created
February 28, 2013 03:30
-
-
Save rboyd/5053955 to your computer and use it in GitHub Desktop.
random string (clojure)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defn rand-str [len] | |
(apply str (take len (repeatedly #(char (+ (rand 26) 65)))))) |
great thanks!
great thanks!
Great thanks!
Came in really handy when needed and saved valuable time. Thanks!
By using a list comprehension, I could improve times by ~30%
(defn rand-str [len]
(apply str
(for [i (range len)]
(char (+ (rand 26) 65))))))
user=> (defn bench [len]
#_=> (time (rand-str-old len))
#_=> (time (rand-str len))
#_=> nil)
#'user/bench
user=> (bench 1e+9)
"Elapsed time: 149173.812436 msecs"
"Elapsed time: 109004.200836 msecs"
nil
great thanks!
Appreciate it!
great thanks!
just for fun, and supporting lowercase and capital letters:
(defn rand-letter-str
[len]
(transduce
(map (fn [_]
(let [rnd (rand-int 52)]
(char (+ (mod rnd 26)
(int (if (< rnd 26) \a \A)))))))
str
""
(range len)))
Because we can, here's two more ways to do it and a bench to check the speed for all above mentioned and the two others.
Take your pick :)
(let [rep-rand-str (fn [len] (apply str (take len (repeatedly #(char (+ (rand 26) 65))))))
for-rand-str (fn [len] (apply str (for [i (range len)] (char (+ (rand 26) 65)))))
loop-rand-str (fn [len] (loop [len len r []] (if (< 0 len) (recur (dec len) (conj r (char (+ (rand 26) 65)))) (apply str r))))
reduce-rand-str (fn [len] (apply str (reduce (fn [r l] (conj r (char (+ (rand 26) 65)))) [] (range len))))
transduce-rand-str (fn [len] (transduce (map (fn [_] (let [rnd (rand-int 52)] (char (+ (mod rnd 26) (int (if (< rnd 26) \a \A))))))) str "" (range len)))
bench (fn [len times]
(time (dotimes [_ times] (rep-rand-str len)))
(time (dotimes [_ times] (for-rand-str len)))
(time (dotimes [_ times] (loop-rand-str len)))
(time (dotimes [_ times] (reduce-rand-str len)))
(time (dotimes [_ times] (transduce-rand-str len)))
nil)]
(bench 1e+5 100))
"Elapsed time: 2171.6456 msecs"
"Elapsed time: 1041.4757 msecs"
"Elapsed time: 1352.2245 msecs"
"Elapsed time: 1268.5602 msecs"
"Elapsed time: 121711.7105 msecs"
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
great thanks!