I need to create a random character generator that return a single character. The character should range within the letters of the alphabet, numbers 0 through 9, and some characters like ,.?/-. Any example would be appreciated.
+4
A:
Pick a random number between [0, x), where x is the number of different symbols. Hopefully the choice is uniformly chosen and not predictable :-)
Now choose the symbol representing x.
Profit!
I would start reading up Pseudorandomness and then some common Pseudo-random number generators. Of course, your language hopefully already has a suitable "random" function :-)
pst
2010-06-24 23:26:04
+1 for using a reasonable step -> step -> profit!!! scheme when facing this kind of question.
Scorchio
2010-06-24 23:27:22
+1
A:
Using some simple command line (bash scripting):
$ cat /dev/urandom | tr -cd 'a-z0-9,.?/\-' | head -c 30 | xargs
t315,qeqaszwz6kxv?761rf.cj/7gc
$ cat /dev/urandom | tr -cd 'a-z0-9,.?/\-' | head -c 1 | xargs
f
- cat /dev/urandom: get a random stream of char from the kernel
- tr: keep only char char we want
- head: take only the first
n
chars - xargs: just for adding a
'\n'
char
Nicolas Viennot
2010-06-24 23:35:36
+2
A:
The easiest is to do the following:
- Create a
String alphabet
with the chars that you want. - Say
N = alphabet.length()
- Then we can ask a
java.util.Random
for anint x = nextInt(N)
alphabet.charAt(x)
is a random char from the alphabet
Here's an example:
final String alphabet = "0123456789ABCDE";
final int N = alphabet.length();
Random r = new Random();
for (int i = 0; i < 50; i++) {
System.out.print(alphabet.charAt(r.nextInt(N)));
}
polygenelubricants
2010-06-25 12:56:24