Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get a random int between 1-100 where result is scewed 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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading