The recursive function of a random seed. How should I do it?

I have a recursive function, and inside this function a random element is selected from the array, but no matter what I do, I get 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 is the best way to handle Random in a recursive function?

+5
source share
4 answers

Declare a single (static) instance of the object Randomoutside the scope of your recursive function, and then call the instance from your recursive function.

The default constructor Randomwill automatically sow it with the current timestamp, so you will get the same values ​​again and again, because you are constantly creating a new instance of the object Random.

Edit: , , . Random .

Random r = new Random( Guid.NewGuid().GetHashCode() );
+3

, . , ,

void MyRecursiveFunction() {
  var index=new Random().Next(...);
  ...
}

true, , , " Random()" ( ), .

+2

Random , .

public void Recurse(object param, Random rand)
{

  ...
  var val = rand.Next();
  //use the value ... 
  Recurse(obj, rand);
}

Recurse(arg, new Random());

, - , .

+1
source

I suggest including a random object in a recursive function. This test should prove that you do not always get the same int.

[Test]
    public void TestSpintaxRandom()
    {
        spintaxParser("{|||{|||{|||{|||{|||{|||{|||{|||}}}}}}}}", new Random());
    }

    public String spintaxParser(String s, Random r)
    {
        if (s.Contains('{'))
        {
            var closingBracePosition = s.IndexOf('}');
            var openingBracePosition = closingBracePosition;

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

            var spintaxBlock = s.Substring(openingBracePosition, closingBracePosition - openingBracePosition + 1);
            var items = spintaxBlock.Substring(1, spintaxBlock.Length - 2).Split('|');

            var next = r.Next(items.Length);
            Console.WriteLine(next);
            s = s.Replace(spintaxBlock, items[next]);

            return spintaxParser(s, r);
        }

        return s;
    }
0
source

All Articles