Search code examples
iosrandom

Synchronized random numbers


I have 2 devices, and I am looking for a way to sync random number generation between them.

More background: The 2 devices connect, one device sends the other a file containing a data set. The data set is then loaded on both devices. The data is displayed with randomization at various levels. I want the display to be synced between the devices, however still randomized.

A conceptual example: Take a stack of pictures. A copy of the stack is sent to the remote device and stored for future use. The stacks are then shuffled the same way on both devices so that drawing the first picture on each device will result in the same output. This is overly simplified, there are far more random numbers required in my application so optimizations such as sharing the sort order are not applicable...

Breaking it down: I need a simple way to draw from the same random number pool on 2 devices. I do not know how many random draws may occur before the devices sync, but once synced it should be predictable that they will draw the same number of random numbers since they are using the same data sets, however there is a chance one could draw more than the other before proceeding to the next batch (which would require a re-sync of the random data).

I'm looking to avoid having to transfer sort orders, position info etc. for each entity already transferred in the data set at display time (which also raises structural concerns since the project wasn't initially designed to share that info) by being able to generate the same placement, which requires the random numbers come out in the same order.

Any thoughts or suggestions would be much appreciated.


Solution

  • You can use an LCG algorithm and set the same seed for the generation. Because an LCG algorithm is deterministic, as long as you seed both devices with the same seed, they will produce exactly the same pseudo-random numbers.

    You can find more information on the LCG algorithm here:

    Linear congruential generator

    This LCG is used for example by java.util.Random.