[REBOL] Re: random string
From: joel:neely:fedex at: 10-Apr-2002 6:51
Hi, John,
A few suggestions...
[john_kenyon--mlc--com--au] wrote:
> Is there a better way of creating a random string of 8
> characters than the folowing?
>
> salt-string: copy ""
> loop 8 [ append salt-string to-char add random 78 48 ]
>
I'm assuming that the 8 is more or less accidental; there
might be a future need to create random strings of other
lengths...
If you pre-allocate the string to the desired length, the
interpreter won't waste time re-allocating and copying as
the string grows.
Since APPEND is a mezzanine, you can save time (in *very*
small increments, but they add up in deeply nested loops)
by directly saying INSERT TAIL instead.
RANDOM returns a result that is the same type as its
argument, including the CHAR! type.
You can add (suitably small ;-) integers to CHAR! values;
the result will still be CHAR! typed.
It wasn't clear to me why you wanted strings to contain
only characters between #"1" and #"~". Is there some
application-specific reason? (I assume you're aware that
REBOL is 1-origin in philosophy, rather than 0-origin,
which means that RANDOM 78 will return a value between
1 and 78 inclusive.) In the example below, I assumed
that any printable ASCII (7-bit) characters would do as
well. YMMV, especially if you want the Extended Roman
characters.
Here's a function that combines all of the above...
randstr: func [w [integer!] /local r] [
r: make string! w
loop w [
insert tail r (random #"^^") + 32
]
r
]
which behaves as follows:
>> randstr 8 == "O_YgI,WW"
>> randstr 8 == "2h6`kj}$"
>> randstr 8 == "~]6:$?5f"
>> randstr 8 == "=ZKlbxZX"
>> randstr 8 == "|Zp5RpyH"
>> randstr 8 == "LZp(f`<`"
>> randstr 8 == {k"9EjEBk}
>> randstr 8 == "6m2BqVI3"
>> randstr 8 == "uBz<[ZV9"
Hope this helps!
-jn-
--
; Joel Neely joeldotneelyatfedexdotcom
REBOL [] do [ do func [s] [ foreach [a b] s [prin b] ] sort/skip
do function [s] [t] [ t: "" foreach [a b] s [repend t [b a]] t ] {
| e s m!zauafBpcvekexEohthjJakwLrngohOqrlryRnsctdtiub} 2 ]