How do I generate a rule for more than one option in Bogus?

2k views Asked by At

I have a rule to select an option at random:

    .RuleFor(c=>field, x=>x.PickRandom("Option1", "Option2", "Option3", "Option4"))

With a default value, I can alter the probability of one of the items. I would like to set the probabilities of all four items. Option1 would be picked 50% of the time, Option2 would be picked 30%, then 15% for Option3, and 5% for Option4.

I would like to use a WeightedRandom:

    .RuleFor(c=>field, x=>PickWeightedRandom(valueArray, weightArray)

There is no such method as PickWeightedRandom, but WeightedRandom is a method in the Randomizer class. How do I get the WeightedRandom to work?

EDIT: Maybe an extension method?

2

There are 2 answers

0
Brian Chavez On

The following seems to work:

void Main()
{
   var items = new []{"kiwi", "orange", "cherry", "apple"};
   var weights = new[]{0.1f, 0.1f, 0.2f, 0.6f};
   
   var faveFaker = new Faker<Favorite>()
      .RuleFor(x => x.Fruit, f => f.Random.WeightedRandom(items, weights));
      
   faveFaker.Generate(10).Dump();
}

public class Favorite
{
   public string Fruit {get;set;}
}

enter image description here


Of course, using C# extension methods are always an excellent way to extend Bogus to best suit your API needs:

void Main()
{  
   var faveFaker = new Faker<Favorite>()
      .RuleFor(x => x.Fruit, f => f.WeightedRandom( ("kiwi",   0.1f), ("orange", 0.1f),
                                                    ("cherry", 0.2f), ("apple",  0.6f)) );
      
   faveFaker.Generate(10).Dump();
}

public class Favorite
{
   public string Fruit {get;set;}
}

public static class MyExtensionsForBogus
{
   public static T WeightedRandom<T>(this Faker f, params (T item, float weight)[] items)
   {
      var weights = items.Select(i => i.weight).ToArray();
      var choices = items.Select(i => i.item).ToArray();
      return f.Random.WeightedRandom(choices, weights);
   }
}

enter image description here

0
Cakemeister On

One answer is to pick the random string somewhere else, then use the => operator to point to the result.

    public static string PickAString(string[] items, float[] weights)
    {
        // hopefully all the weights will add up to 1. If not, this method may throw for array out of bounds.
        // Also, it would be best if the number of items in each array is the same, to prevent out of bounds exception.

        // generate a number from 0 to less than 1
        double randomValue = random.NextDouble();
        double weightSum = 0;
        for (int i = 0; i < items.Length; i++)
        {
            weightSum += weights[i];
            if (randomValue < weightSum)
                return items[i];
        }
        return null; // if the weights don't add up.
    }

    .RuleFor(c => c.field, _ =>
    { 
        return PickAString(values, weights); 
    }) 

This works, but it would be more elegant to add this to the library.