views:

80

answers:

1

I'm trying to generate a string of a random length which consists out of random chars.

To do so I have this code:

class Program
{
    static void Main(string[] args)
    {
        for (int i = 0; i < 1000; i++)
        {
            MyString test = new MyString();

            test.Random();
            Console.WriteLine(test.Value);
        }
        Console.ReadLine();
    }
}

public class MyString
{
    private string value = string.Empty;
    private Random r = new Random();

    public string Value
    {
        get { return this.value; }
        set { this.value = value; }
    }

    public void Random()
    {
        int length = (r.Next() % (100)) + 1;
        for(int i = 0; i < length; i++)
        {
            value = value + RandomChar();
        }  
    }

    public char RandomChar()
    {
        // 32 to 126
        int c = (r.Next() % 95) + 32;
        char ch = (char)c;
        return ch;
    }
}

Now, lets look at a part of the output:

alt text

As you can see, the output is far from random, it contains a lot of repeating strings. How is this possible, and how do I solve it?

+9  A: 

It looks like you are creating a new instance of the Random class every time your MyString constructor is called. The Random class probably seeds itself based on the current time (to some resolution). Random number generators seeded with the same value will generate the same pseudo-random sequence.

The solution is to construct one instance of Random and use that everywhere.

Greg Hewgill
Good answer. From the doc: "However, because the clock has finite resolution, using the parameterless constructor to create different Random objects in close succession creates random number generators that produce identical sequences of random numbers." http://msdn.microsoft.com/en-us/library/system.random.aspx
Kirk Woll
+1 As a quick fix, consider making your `Random` instance static -- it will likely change the distribution of characters since there is only one `Random` instance.
Steve Guidi
w0w! That's a quick answer :D Thanks, it works great now!
@r0h: Just don't use this in a cryptography scenario. Probably great for test code, though.
Merlyn Morgan-Graham