mercredi 29 avril 2020

C# Random generates different value with the same seed

I am writing a generator of maths problems for my coursework project and I encountered an issue that I can bypass in an ugly way, but I would like to understand why is it happening.

I have a constructor that takes an integer and assigns it to seed inside of the Random(seed). Then I go on to generate all of the values using that random.

There are two possible modes for generating. I either generate a block of 100 problems and then randomly pick a couple among those 100 and display them in an HTML document. It works fine. However right after generating a block, if I try to generate those problems using its number, my Random gives me different values for the same variables.

However, when I retry to handpick a problem with that number, it works fine on a second attempt giving me the problem that I wanted. Same thing when I run the program and go straight to hand picking a particular problem.

Here is the constructor

readonly Random rng = new Random(seed);
    public Level2(int seedVal)
    {
        seed = seedVal;
        Key = GenerateKey(seedVal)+"2";
        GenerateXval(seedVal);
        GenerateValuesGeneral();
        this.htmlFormula = GenerateProblem(seedVal % 4);
    }

Here is the part of the code that generates a block of problems

private void GenerateTasksLevel2(int n)
    {
        List<string> problems = new List<string>();
        for (int i = 0; i < n; i++)
        {
            Level2 task = new Level2(i);
            problems.Add(task.htmlFormula);
        }
        Problems = problems;
    }



Aucun commentaire:

Enregistrer un commentaire