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?
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() );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With