N
N
nikmil2019-03-20 10:19:07
C++ / C#
nikmil, 2019-03-20 10:19:07

How to predict random by ticks?

Hello, I was interested in one topic with randomness.
I found a program that creates random numbers. I read that the numbers are not random, but pseudo-random, and they depend on time (ticks).
So is it possible to specify a certain time in the program for random, according to which he would be guided and generate a random number?

class Program
    {
        static void Main(string[] args)
        {
            Random rnd = new Random();
            for (int i = 0; i < 1; i++)
                Console.WriteLine("{0,4}", rnd.Next(50, 501));
            Console.ReadKey();
        }
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
Foggy Finder, 2019-03-20
@nikmil

If you use the default constructor of the Random class, then Environment.TickCount will be used as the seed - the time elapsed since the system booted in milliseconds.
In order to generate the same sequence, there is a separate overload that takes a "seed" - a value that is used to select the seed. For example, you want to use a specific time

var ts = new TimeSpan(10, 10, 10);
var rnd = new Random((int)ts.TotalMilliseconds);

Thus, the same sequence will be generated.
for (int i = 0; i < 1; i++)
    Console.WriteLine("{0,4}", rnd.Next(50, 501)); // 265

You can also look at the source code ( Random.cs ) and find out the implementation so that the "prediction" is completely accurate :-)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question