I am wanting to generate the same random sequence (of numbers or characters) based on a given "seed" value.
Using the standard Randomize
function does not seem to have such an option.
For example in C# you can initialize the Random function with a seed value (Random seed c#).
How can I achieve something similar in Delphi?
CodePudding user response:
You only need to assign a particular value to the RandSeed
global variable.
Actually, I'm almost surprised you asked, because you clearly know of the Randomize
function, the documentation for which states the following:
The random number generator should be initialized by making a call to
Randomize
, or by assigning a value toRandSeed
.
CodePudding user response:
In general, pseudorandom number generators have internal state, in order to calculate the next number. So they are not thread-safe, and require an instance per thread. For encapsulated thread-safe random numbers, you can use a suitable hash function, such as xxHash, and pass it a seed and a counter that you increment after each call in the thread.
There is a Delphi implementation of xxHash here: https://github.com/Xor-el/xxHashPascal
For general use, it's easy to make several versions in 1, 2 or 3 dimensions as needed, and return either floating point in 0..1 or integers in a range.