3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Clojureでランダムな文字列を生成してみる

3
Posted at

長さを与えたらその長さ分のランダムな文字列を返す関数を作ってみる。
デフォルトでは英数62文字の中からランダムに文字選択される。
文字範囲は第2引数で指定できるようにもする。

rand-str.clj
(defn range-size
  ([start size] (range-size start size 1))
  ([start size step]
    {:pre[(integer? size)]}
    (take size (range start (+ start (* size step)) step))))

(defn rand-str
  ([n] (rand-str n (mapcat #(apply range-size %) [[48 10] [65 26] [97 26]])))
  ([n charseq] (apply str (map char (repeatedly n #(rand-nth charseq))))))

するとこんな感じでできた。

user=> (range-size 50 5)
(50 51 52 53 54)
user=> (rand-str 20)
"195Tbl1nE8ME0QGEwJl7"
user=> (rand-str 20 "abc")
"cbabbbcabbbaaaabcaca"
3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?