Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a random list of strings using recursion?

Tags:

string

c#

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?

like image 959
Kasun Peiris Avatar asked Aug 26 '10 06:08

Kasun Peiris


1 Answers

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)));
like image 193
Timwi Avatar answered Oct 20 '22 17:10

Timwi