tags:

views:

45

answers:

2

I want to generate a random list of strings containing only alphanumeric characters. The length of the string can be of any size. Is there any way to do this using recursion?

+2  A: 

There is no need for recursion in this. Simply write down the characters you want in your string, for example:

string allowedCharacters = "abcdefghijklmnopqrstuvwxyz0123456789";

Then you can simply grab characters from this by random:

Random rnd = new Random();
string randomString(int length)
{
    int num = allowedCharacters.Length;
    return new string(Enumerable.Range(0, length)
           .Select(i => allowedCharacters[rnd.Next(0, num)])
           .ToArray());
}

Finally, you can use this to generate a string of a random length:

// Outputs a random string of a length between 5 and 49 characters
Console.WriteLine(randomString(rnd.Next(5, 50)));
Timwi
I am still a little new to the use of C#. No offense, but isn't there a simpler way to do this? I mean the whole "return new string(Enumerable.Range(0, length) .Select(i => allowedCharacters[rnd.Next(0, num)]) .ToArray());"has got me a little confusing.
kash
That depends on how you define “simple”. Of course I can write it without `Enumerable.Range` and without `Select`, but it would be more verbose. (It would also be faster, but that’s not usually part of the definition of “simple”.)
Timwi
+3  A: 

Since you explicitly asked for recursion, here is a recursive solution. It’s very slow, though.

static string allowedCharacters = "abcdefghijklmnopqrstuvwxyz0123456789";
static Random rnd = new Random();
static string randomString(int length)
{
    if (length == 0)
        return "";
    return allowedCharacters[rnd.Next(0, allowedCharacters.Length)]
           + randomString(length - 1);   // This is the recursive call.
}

Now you can use this to generate a string of a random length:

// Outputs a random string of a length between 5 and 49 characters
Console.WriteLine(randomString(rnd.Next(5, 50)));
Timwi
Thanks for the help.
kash