vendredi 1 avril 2022

Generate a list of (count) Random Numbers that total to a specified average value of (avg)

  1. I'm trying to make a game which randomly generates characters classes and stats

  2. The characters class effects the amount of substats they have

  3. The first stat which is randomly generated is call overall which every class has and is an integer randomly assigned a value 1-99

  4. based on this overall number, I want to create a function which randomly generates the classes substats. Each of these classes has a different number of substats. So with this function I want to pass the overall stat to serve as (avg) the average of the list. The number of substats to serve as (count) the length of the list. And a minimum and maximum value, to prevent stats from getting to high and too low.

This is a C# application and while I can figure out for myself how to create a list of y random numbers, the averaging is proving to be difficult. I've found a solution which kind of works but it doesn't average out to a true value of the overall, just gets it within the ballpark of a few numbers of the average. I've listed that function below.

public List<int> createRandomNumberList(int avg, int count, int min, int max)
        {
            var rnd = new Random();
            var numbers = new List<int>();
            for (var i = 0; i < count; i++)
            {
                var random1 = rnd.Next(min, avg + 1);
                var random2 = rnd.Next(avg + 2, max + 1);
                var randoms = new List<int>();
                randoms.AddRange(Enumerable.Repeat<int>(random2, avg - min));
                randoms.AddRange(Enumerable.Repeat<int>(random1, max - avg));

                var generatedNumber = randoms[rnd.Next(randoms.Count)];
                numbers.Add(generatedNumber);
            }
            return numbers;
        }

Any help would be appreciated




Aucun commentaire:

Enregistrer un commentaire