-4

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?

RaelB
  • 3,301
  • 5
  • 35
  • 55
  • 1
    The answer is in the documentation of the function you mentioned https://docwiki.embarcadero.com/Libraries/en/System.Randomize – David Heffernan Aug 16 '22 at 17:31
  • @RaelB: But beware that it is not allowed to ask for library recommendations on Stack Overflow. – Andreas Rejbrand Aug 16 '22 at 18:36
  • 1
    What you are looking here is `Pseudorandom number generator` algorithm. But it is hard to make any specific recommendation because there have been so many different algorithms made over the years. Some are purely math based and therefore quite easily implemented but others might rely on specific hardware support (hardware based acceleration). Most PRNG algorithms accept one input value (starting seed) while some are even designed to accept multiple input values which can then affect the random distribution of the returned values and how quickly they might start repeating. – SilverWarior Aug 16 '22 at 20:03

2 Answers2

4

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 to RandSeed.

Andreas Rejbrand
  • 105,602
  • 8
  • 282
  • 384
-1

The question did not mention thread safety as a requirement, but the OP specified that in comments.

In general, pseudorandom number generators have internal state, in order to calculate the next number. So they cannot be assumed to be thread-safe, and require an instance per thread. For encapsulated thread-safe random numbers, one alternative is to use a suitably good 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.

Garth Thornton
  • 94
  • 1
  • 1
  • 7