lundi 27 mars 2017

Elegant way to control Random Seed if necessary

I have an application that more or less spits out randomly generated data. The short is, we have collections of data (first names, last names, etc.) and we get a random index of each collection and return the data. Right now, there's lots of calls that look like this...

Random rando = new Random()
int index = rando.Next(collection.Count());

Which is fine, and works as intended but what I am interested in introducing is a way to reproduce data sets if the need arises. This can be done by capturing/controlling the seed used to create the Random object. My idea is as follows:

A static class that's essentially a wrapper around a Random object. It looks like this;

public static class SeedGovernor
{
    private static Random random = null;
    private static int masterSeed; 

    public static void SetSeed()
    {
        if (random != null) random = null;
        Random master = new Random();
        masterSeed = master.Next();
        random = new Random(masterSeed);
    }

    public static void SetSeed(int sd)
    {
        if (random != null) random = null;
        masterSeed = sd;
        random = new Random(masterSeed);
    }

    public static int GetMasterSeed()
    {
        return masterSeed;
    }

    public static int GetRandomInt()
    {
        return random.Next();
    }

    public static int GetRandomInt(int max)
    {
        return random.Next(max);
    }

    public static int GetRandomInt(int min, int max)
    {
        return random.Next(min, max);
    }

    public static double GetRandomDouble()
    {
        return random.NextDouble();
    }
}

At run time, we can either define the seed we want to use using SetSeed(int sd) or let it be randomly chosen (but still capturing the seed for future use) using SetSeed(). Then, we simply make calls to the static methods we need.

int index = SeedGovernor.GetRandomInt(collection.Count);

Is there a better, more elegant approach to this? Is there anything wrong with this implementation that I should be concerned with? The testing I've done so far appears to be working as I intended.




Aucun commentaire:

Enregistrer un commentaire