Random alphanumeric string
Salih Dincer
salihdb at hotmail.com
Mon Jan 30 18:31:06 UTC 2023
It could be more flexible if it could be used as a range without
packing this code too much:
```d
auto randomAlphanumeric(string S)(size_t len)
{
import std.array : array;
import std.random : choice, Random, unpredictableSeed;
import std.range : generate, take;
auto rnd = Random(unpredictableSeed);
auto gen = generate!(() => S.array.choice(rnd));
return gen.take(len);
}
import std.ascii, std.stdio;
void main()
{
auto str = 16.randomAlphanumeric!lowercase;
auto hex = 16.randomAlphanumeric!hexDigits;
foreach(c; str)
{
c.write;
}
writeln("\n", hex); /* Prints:
tqapxlqouvbpgsia
862C234EE3D9CFC4
*/
}
```
I would prefer to use an enum as it is simple. For example, it's
as simple as this:
```d
generate!(function char() => uniform!Enum)
```
Put that in a function and enums of type char into a struct as
well:
```d
auto randomFromEnumerate(E)(size_t len)
{
import std.random : rnd = uniform;
import std.range : generate, take;
return generate!(function char() => rnd!E).take(len);
}
struct E {
enum num {
o = '0', p, q, r, s, t, u, v, w, x,
}
enum hex {
o = '0', p, q, r, s, t, u, v, w, x,
a = 'A', b, c, d, e, f
}
enum dna {
a = 'A', c = 'C', g = 'G', t = 'T'
}
enum lowercase {
a = 'a', b, c, d, e, f, g, h, i, j, k, l,
m, n, o, p, q, r, s, t, u, v, w, x, y, z
}
}
void main()
{
10.randomFromEnumerate!(E.dna).writeln;
// CGTGAGGGTC
}
```
SDB at 79
More information about the Digitalmars-d
mailing list