views:

90

answers:

3

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: 
  1. Pick a random number between [0, x), where x is the number of different symbols. Hopefully the choice is uniformly chosen and not predictable :-)

  2. Now choose the symbol representing x.

  3. 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
+1 for using a reasonable step -> step -> profit!!! scheme when facing this kind of question.
Scorchio
+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
Beautiful. I like it :-)
pst
+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 an int 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