1
 static void Main(string[] args) { //random number gen Console.WriteLine("Array Random Number:"); randomGenA(); Console.WriteLine("------------------"); //LIST: random movie picker... Console.WriteLine("List Random Number:"); randomGenB(); Console.WriteLine("------------------"); Console.ReadLine(); } static void randomGenA() { Random randomA = new Random(); int randomNumA = randomA.Next(51); Console.WriteLine(randomNumA); } static void randomGenB() { Random randomB = new Random(); int randomNumB = randomB.Next(0,51); Console.WriteLine(randomNum); } } 

I wanted them both to produce two different random numbers but instead I keep getting the same random number from both of them. Why does it do this?

6
  • 2
    The time difference between the instantiations of these two Random objects is minimal, causing them to have the same seed. Introduce a delay (please don't) or share the Random instance. Commented Sep 2, 2015 at 20:28
  • Possible duplicate of this question Commented Sep 2, 2015 at 20:30
  • thanks for the explanation! Commented Sep 2, 2015 at 20:30
  • add System.Threading.Thread.Sleep(50); between your method call Commented Sep 2, 2015 at 20:32
  • 2
    create one Random randomB = new Random(); in class and use it in both methods. Commented Sep 2, 2015 at 20:32

2 Answers 2

3

Declare a class level random and use it in your methods:

private static Random _random = new Random(); 

Your methods would look like:

static void randomGenA() { int randomNumA = _random.Next(51); Console.WriteLine(randomNumA); } static void randomGenB() { int randomNumB = _random.Next(0,51); Console.WriteLine(randomNum); } 

Check this out for further reading: http://www.dotnetperls.com/random

Sign up to request clarification or add additional context in comments.

Comments

0

As per the documentation:

https://msdn.microsoft.com/en-us/library/system.random%28v=vs.110%29.aspx

Two Randoms with the same seed will provide the same sequence of numbers. Simply don't use the same seed. If you don't specify a seed, it uses the system time. Wait some time between the two instantiations and it will use two different system times.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.