Skip to content

[Enhancement] Add the possibility to generate a randomly selected value based on the specified probabilities #71

@lpeyr

Description

@lpeyr

Enhancement

Add the possibility to generate a randomly selected value based on the specified probabilities.

Other informations

using System;
using System.Collections.Generic;

public static class RandomValueGenerator
{
    public static T GetRandomValue<T>(Dictionary<T, double> probabilities)
    {
        double totalProbability = 0.0;
        foreach (double probability in probabilities.Values)
        {
            totalProbability += probability;
        }

        if (totalProbability != 1.0)
        {
            throw new ArgumentException("The sum of probabilities must be 1.");
        }

        double randomValue = new Random().NextDouble();
        double cumulativeProbability = 0.0;
        foreach (T value in probabilities.Keys)
        {
            cumulativeProbability += probabilities[value];
            if (randomValue < cumulativeProbability)
            {
                return value;
            }
        }

        throw new Exception("An unexpected error occurred while selecting a random value.");
    }
}

Metadata

Metadata

Assignees

Labels

coreIssues related to the "Core" moduleenhancementNew feature or requestroadmapFeature of the roadmapvNextIssues planed for the next version

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions