Search code examples
c#math

How to get a random int between 1-100 where result is skewed towards X?


I want to generate a random age, lets say between 1-100. My "target" age is around 40, so I want most generated ages to be roughly 30-50, but still a few generated outside this smaller range. Is there anyway to do this?

Preferably using C# library.


Solution

  • You don't need a C# Library. You can achieve this via Math.

    using System;
    
    class Program
    {
        static void Main()
        {
            int targetAge = 40;
            int minAge = 1;
            int maxAge = 100;
    
            int generatedAge = GenerateRandomAge(targetAge, minAge, maxAge);
            Console.WriteLine($"Generated Age: {generatedAge}");
        }
    
        static int GenerateRandomAge(int targetAge, int minAge, int maxAge)
        {
            Random random = new Random();
            double mean = targetAge; // Mean of the distribution
            double standardDeviation = 8; // Standard deviation controls the spread of values
            double u1 = 1.0 - random.NextDouble();
            double u2 = 1.0 - random.NextDouble();
            double randStdNormal = Math.Sqrt(-2.0 * Math.Log(u1)) * Math.Sin(2.0 * Math.PI * u2);
            double randNormal = mean + standardDeviation * randStdNormal;
            int generatedAge = (int)Math.Round(Math.Clamp(randNormal, minAge, maxAge)); // Ensure the generated value is within the specified range
            return generatedAge;
        }
    }
    

    enter image description here

    Refer the working code here