jeudi 19 novembre 2020

C# How to generate a random number in a range, biased toward the low end of the range?

Helo! My code is:

    class Program
        {
            static void Main(string[] args)
            {
                for (int x = 0; x < 15000; x++)
                {
                    int minValue = 1;
                    int maxValue = 1400;
                var rand = new Random();

                List<float> weights = new List<float>();
                List<float> numbers = new List<float>();
                for (int i = minValue; i <= maxValue; i++)
                {
                    weights.Add((int)Math.Pow(i, 0.4));
                    numbers.Add(i);
                }
                weights.Reverse();

                int weightSum = 0;
                foreach (int weight in weights)
                {
                    weightSum += weight;
                }

                List<int> possibleNumberList = new List<int>();

                float randomNumber = rand.Next(minValue, weightSum);

                float leastDifference = 2000000000f;
                int leastDifferenceNumberIndex = -1;
                for (int weightIndex = 0; weightIndex < weights.Count - 1; weightIndex++)
                {
                    if (Math.Abs(weights[weightIndex] - randomNumber) == leastDifference)
                    {
                        leastDifference = Math.Abs(weights[weightIndex] - randomNumber);
                        leastDifferenceNumberIndex = weightIndex;

                        possibleNumberList.Add(weightIndex);
                    }
                    else if (Math.Abs(weights[weightIndex] - randomNumber) < leastDifference)
                    {
                        leastDifference = Math.Abs(weights[weightIndex] - randomNumber);
                        leastDifferenceNumberIndex = weightIndex;
                        possibleNumberList = new List<int>();
                        possibleNumberList.Add(weightIndex);
                    }
                }

                var randFromListR = new Random();

                int listCunt = possibleNumberList.Count;
                int index = randFromListR.Next(0, listCunt);
                WWriteStringToNewLine(possibleNumberList[index].ToString());
            }
        }
    }

My goal is to have a list or array shown in the image peresentatin

Although my max value for me would be 1400.

With my code I can only achieve the following output: bad

If we zoom in, we can see that there are some higher numbers but generated only once. badZoom

If we set the code's max value to 10 the output is the following:

{3: 2837, 0: 2813, 4: 2781, 2: 2761, 1: 2759, 5: 273, 6: 264, 7: 262, 8: 250}

Max value 10

What could I change on this code to work correctly? What do you suggest? You can even give me a whole different code.




Aucun commentaire:

Enregistrer un commentaire