samedi 7 janvier 2017

A variation on issues with random numbers in C#

I'm working on a program which creates a large number of instances of an object belonging to a class I've created. Every one of these objects is supposed to contain a list of random numbers, and I want a different random list for each object. At present I create the seed for the random numbers inside the definition of the class (see below), and hence I get the same list in every object.

I understand how the random number generation works (and have read through a lot of other answers about similar issues), so I know that the problem is that the seeds are all being created too close in time. However, I don't know how to create a single static seed which will be used every time I use an object of this class. Is there a way to use a static random number seed as an argument when I instantiate a new object? Or is there a better solution?

Thanks.

public class Room
    {

        static System.Random x = new System.Random();

        public List<int> birthdays = new List<int>();

        public int year;

        public Room(int y)
        {

            year = y;
        }



        public void Fill(int j)
        {
            System.Console.WriteLine(x.Next(1, year));
            birthdays.Add(x.Next(1, year));
        }

        public bool Check(int p, int d, int j)
        {
            for (int q = 0; q < j; q++)
            {
                int total = 0;
                for (int y = 0; y < j; y++)
                {
                    if (birthdays[y] - birthdays[q] <= d) { total += 1; };

                    if (total >= p)
                    { return true; }
                }

            }
            return false;


        }

    }




Aucun commentaire:

Enregistrer un commentaire