Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random number In C# [duplicate]

Tags:

c#

random

Possible Duplicate:
Random number generator not working the way I had planned (C#)

I created a method that returns me a random number:

public static int SelectRandomMachine(int max)
{
int seed = (int)DateTime.Now.Ticks;
Random rndNumber = new Random(seed);
int randMachine = rndNumber.Next(0, max);
return randMachine;
}

if I call the method two times, currently it's return me the same random number:

randM1 = SelectRandomMachine(maxNumber);
randM2 = SelectRandomMachine(maxNumber);

any suggestion would be highly appreciated.

like image 873
MKS Avatar asked Dec 29 '25 02:12

MKS


1 Answers

Hint look at this line:

int seed = (int)DateTime.Now.Ticks;

If you execute that line twice in quick succession, what do you think the values will be?

For example:

int seed1 = (int)DateTime.Now.Ticks;
int seed2 = (int)DateTime.Now.Ticks;

// Write it out *after* executing; console output can take a while
Console.WriteLine(seed1);
Console.WriteLine(seed2);

See my article on randomness for solutions and more information.

EDIT: Here's a quick and dirty example of the lack of thread safety causing problems:

using System.Collections.Generic;
using System.Threading;

class Program
{
    const int Iterations = 1000000;
    static readonly Random rng = new Random();

    static void Main(string[] args)
    {
        List<Thread> threads = new List<Thread>();
        for (int i = 0;  i < 8; i++)
        {
            Thread t = new Thread(ExerciseRandom);
            threads.Add(t);
            t.Start();
        }
        foreach (Thread t in threads)
        {
            t.Join();
        }
        Console.WriteLine(rng.Next());
        Console.WriteLine(rng.Next());
        Console.WriteLine(rng.Next());
    }

    static void ExerciseRandom()
    {
        for (int i = 0; i < Iterations; i++)
        {
            rng.Next();
        }
    }
}

Output on my box:

0
0
0
like image 91
Jon Skeet Avatar answered Dec 30 '25 15:12

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!