giacomelli / GeneticSharp

GeneticSharp is a fast, extensible, multi-platform and multithreading C# Genetic Algorithm library that simplifies the development of applications using Genetic Algorithms (GAs).
MIT License
1.27k stars 332 forks source link

Suggestion: Add an ability to set PRNG's initial seed #62

Closed dxball closed 2 years ago

dxball commented 5 years ago

Is your feature request related to a problem? Please describe. Sometimes I need to generate the same result with the same parameter, so the fixed PRNG seed will be one of the ways to do this.

Describe the solution you'd like Add a constructor to RandomizationBase, and implement in all Randomization class

public abstract class RandomizationBase : IRandomization
{
    protected readonly int seed;
    public RandomizationBase() : this((int)DateTime.Now.Ticks) { }
    public RandomizationBase(int seed) { this. seed = seed; }
}
giacomelli commented 2 years ago

I ended up creating two static methods called ResetSeed for BasicRandomization and FastRandomization, because the way that they work right now, as thread-safe, the constructor approach wouldn't work.

Bellow a sample from a unit test showing how to use the ResetSeed method:

[Test]
public void ResetSeed_GetInt_SameResults()
{
   // Resets the seed for the first time.
    FastRandomRandomization.ResetSeed(1);

    var target = new FastRandomRandomization();
    var actual = new int[10];

    for (int i = 0; i < actual.Length; i++)
    {
        actual[i] = target.GetInt(int.MinValue, int.MaxValue);
    }

   // Resets the seed again with the same value, so the pseudorandom values generated by FastRandomRandomization will follow the same order.
   FastRandomRandomization.ResetSeed(1);

    for (int i = 0; i < actual.Length; i++)
    {
        Assert.AreEqual(actual[i], target.GetInt(int.MinValue, int.MaxValue));
    }
}