Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random Seed Recursive Function. How do I do it?

Tags:

c#

I have a recursive function, and within the function a random element from an array is selected, but no matter what I do I keep getting the same seed.

static Random rand = new Random();
public String spintaxParser(String s)
    {
        if (s.Contains('{'))
        {
            int closingBracePosition = s.IndexOf('}');
            int openingBracePosition = closingBracePosition;

            while (!s[openingBracePosition].Equals('{'))
                openingBracePosition--;

            String spintaxBlock = s.Substring(openingBracePosition, closingBracePosition - openingBracePosition + 1);

            String[] items = spintaxBlock.Substring(1, spintaxBlock.Length - 2).Split('|');


            s = s.Replace(spintaxBlock, items[rand.Next(items.Length)]);

            return spintaxParser(s);
        }
        else
        {
            return s;
        }
    }

What's the best way to handle Random in a recursive function?

like image 325
Sian Jakey Ellis Avatar asked Nov 04 '11 14:11

Sian Jakey Ellis


1 Answers

Declare a single (static) instance of the Random object outside the scope of your recursive function, then invoke the instance from inside your recursive function.

The default constructor of Random will automatically seed it with the current timestamp, so you're getting the same values over and over because you're constantly creating a new instance of the Random object.

Edit: Also, you could try this, although it's definitely not ideal. I would prefer a single Random instance or a static seed over this method.

Random r = new Random( Guid.NewGuid().GetHashCode() );
like image 157
Brandon Moretz Avatar answered Sep 23 '22 23:09

Brandon Moretz