0

I'm using the System.Random function to create/generate a seed for random numbers, then using the Next() for following numbers, but much like in c++, the "rng" gets me the same results of random numbers every time. But in c++ that was solved by clearing the seed in c++ so I was wondering if that also possible in c#?

Stifpy
  • 19
  • 4
  • "System.Random" is not a function... So it is very hard to see what you are doing to get "the same results"... (Clearly you've checked https://stackoverflow.com/questions/767999/random-number-generator-only-generating-one-random-number) – Alexei Levenkov Feb 01 '19 at 03:19

1 Answers1

5

You most likely use a new instance of Random every time. You should not instantiate new Random(seed_here) repeatably.

Random r = new Random(); //Do this once - keep it as a (static if needed) class field 
     
for (int i = 0; i < 10; i++) {
     Console.WriteLine($"{r.Next()}");
}

Update

Here's a more sophisticated example:

class MyClass
{
    //You should use a better seed, 1234 is here just for the example
    Random r1 = new Random(1234); // You may even make it `static readonly`

    public void BadMethod()
    {
        // new Random everytime we call the method = bad (in most cases)
        Random r2 = new Random(1234); 

        for (int i = 0; i < 3; i++)
        {
            Console.WriteLine($"{i + 1}. {r2.Next()}");
        }
    }

    public void GoodMethod()
    {

        for (int i = 0; i < 3; i++)
        {
            Console.WriteLine($"{i+1}. {r1.Next()}");
        }
    }
}
class Program
{
    static void Main(string[] args)
    {
        var m = new MyClass();

        m.BadMethod();
        m.BadMethod();
        m.GoodMethod();
        m.GoodMethod();

    }
}

Output

1. 857019877
2. 1923929452
3. 685483091    
1. 857019877  <--- Repeats
2. 1923929452
3. 685483091
1. 857019877
2. 1923929452
3. 685483091
1. 2033103372 <--- Phew! It's a new number
2. 728933312
3. 2037485757
Community
  • 1
  • 1
tymtam
  • 31,798
  • 8
  • 86
  • 126