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))))))
@carbon-hvze
Copy link

great thanks!

@hexiecs
Copy link

hexiecs commented Jan 8, 2020

great thanks!

@jakebasile
Copy link

great thanks!

@andyfry01
Copy link

Great thanks!

@euporos
Copy link

euporos commented Feb 22, 2021

Came in really handy when needed and saved valuable time. Thanks!

@loeschzwerg
Copy link

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

@elmehalawi
Copy link

great thanks!

@vandyand
Copy link

Appreciate it!

@benjamin-asdf
Copy link

great thanks!

@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