「ランダム文字列」をGaucheで解いてみる
お題:ランダム文字列 - No Programming, No Lifeを書いてみる。
すっきり。#[\w]は文字集合、\wは単語を構成する文字の集合でa-zA-Z_。#[a-zA-Z0-9_]でもいいかな。
char-set->stringで文字集合を文字列に変換するためにsrfi-14
文字列をshuffleでシャッフルするのにgauche.sequence
16文字抜き打すのにsrfi-13のstring-takeを使っています。
追記
さっき
(use gauche.sequence) (use srfi-13) (use srfi-14) (string-take (shuffle (char-set->string #[a-zA-Z0-9_])) 16)
こんなの書いてましたが誤りです。これだと同じ文字が2連続しない。ランダムではない。恥ずかしい。
これでどうだ!
(use gauche.sequence) (use srfi-14) (use srfi-42) (string-ec (: i 16) (~ (shuffle (char-set->string #[a-zA-Z0-9_])) 0))
また追記
実行時間をはかろうとしてtimeしたら
gosh> (time (length '(1 2 3)))こんな表示が。 後でググろう… さっきのだと遅いかな、と思って書き直してみたERROR: failed to link /usr/local/Cellar/gauche/0.9.2/lib/gauche-0.9/0.9.2/i386-apple-darwin11.0.1/gauche--auxsys.so dynamically: dlopen(/usr/local/Cellar/gauche/0.9.2/lib/gauche-0.9/0.9.2/i386-apple-darwin11.0.1/gauche--auxsys.so, 10): Symbol not found: _environ
Referenced from: /usr/local/Cellar/gauche/0.9.2/lib/gauche-0.9/0.9.2/i386-apple-darwin11.0.1/gauche--auxsys.so Expected in: flat namespace in /usr/local/Cellar/gauche/0.9.2/lib/gauche-0.9/0.9.2/i386-apple-darwin11.0.1/gauche--auxsys.so Stack Trace: _______________________________________ 0 (sys-times) [unknown location]実行時間をはかる。
前のをちょっと変えたのをa.scmと今のをb.scmに書いて実行する前の
a.scm(use gauche.sequence) (use srfi-14) (use srfi-42) (dotimes (n 1000) (let ((src (char-set->string #[a-zA-Z0-9_]))) (string-ec (: i 16) (~ (shuffle src) 0))))$ time gosh a.scm real 0m1.475s user 0m1.463s sys 0m0.010s今の
b.scm(use srfi-14) (use srfi-27) (use srfi-42) (dotimes (n 1000) (let* ((src (char-set->string #[a-zA-Z0-9_])) (src-len (string-length src))) (string-ec (: i 16) (~ src (random-integer src-len)))))$ time gosh b.scm real 0m0.105s user 0m0.098s sys 0m0.006sもっといい方法があるに違いない。