Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get two programs to have the same sequence of random numbers?

Is it possible for 2 applications (a server and a client) to generate the same sequence of random numbers? What I need is this:

On server:

i1:=randomrange(10,50); //i1 will be 15
i2:=randomrange(10,50); //i2 will be 40
i3:=randomrange(10,50); //i3 will be 20

On client:

i1:=randomrange(10,50); //i1 will be 15
i2:=randomrange(10,50); //i2 will be 40
i3:=randomrange(10,50); //i3 will be 20

The sequence needs to be dependent of a value that the server calculates and sends it to the client

like image 765
new delphi user Avatar asked Mar 11 '23 01:03

new delphi user


2 Answers

Random number generators are typically, in fact, pseudo random. Given the same initial state, the pseudo random number generator (PRNG) will generate the same sequence of numbers.

Typically thia state is provided by means of a seed. If you are using the PRNG provided by the RTL then you set the seed by assigning a value to RandSeed. Use the same seed in each program and you will generate the same values.

If you are using a different PRNG then consult its documentation to find out how to seed it.

like image 130
David Heffernan Avatar answered Mar 12 '23 15:03

David Heffernan


If you want to implement a pseudo random sequence yourself you may start from linear congruential generator. Actually it is very easy

the formula

and there are only 3 restrictions on the a, c and m values

  1. m and c are relatively prime,
  2. a-1 is divisible by all prime factors of m
  3. a-1 is divisible by 4 if m is divisible by 4

See Linear congruential generator wiki for details.

like image 33
Max Abramovich Avatar answered Mar 12 '23 16:03

Max Abramovich