views:

63

answers:

2

I have a problem finding a good algorithm for generating a random letter. I tried with this:

public static char GetLetter()
    {
        int num = random.Next(0, 26);
        char letter = (char)('a' + num);

        return letter;
    }

which I found on the internet, but it generates same letter, or max two of them. For example, if I want to populate 4x4 matrix with random letters using code above, I get:

C C C C
C C C C
C C G G
G G G G

Any ideas or advices for this matter?

+1  A: 

You're almost certainly creating lots of instances of Random instead of using the same instance for all calls. It's hard to say for sure as you haven't shown how the method is being used or where random is declared. I also doubt that that's really the code you're using, as it would only generate 'a'-'z', not 'C' or 'G'.

Read my article on random number generation for a lot more detail on this, but the basic idea is to use one instance of Random.

Jon Skeet
+1  A: 

It sounds like you're instantiating a new instance of your random object before each call to your method.

The default consructor of the Random class takes its seed from the system clock, which means that if you create several instances in close succession they'll use the same seed, which then means that they'll generate the same sequence of random numbers.

You should create a single instance of the Random class and re-use that same instance every time your method is called.

LukeH