Skip to content

Instantly share code, notes, and snippets.

@rboyd
Created February 28, 2013 03:30
Show Gist options
  • Save rboyd/5053955 to your computer and use it in GitHub Desktop.
Save rboyd/5053955 to your computer and use it in GitHub Desktop.
random string (clojure)
(defn rand-str [len]
(apply str (take len (repeatedly #(char (+ (rand 26) 65))))))
@solussd
Copy link

solussd commented Jun 8, 2022

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)))

@LouDnl
Copy link

LouDnl commented Mar 23, 2023

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