首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Bogus中为多个选项生成规则?

如何在Bogus中为多个选项生成规则?
EN

Stack Overflow用户
提问于 2021-01-22 00:07:28
回答 2查看 259关注 0票数 1

我有一个随机选择选项的规则:

代码语言:javascript
复制
    .RuleFor(c=>field, x=>x.PickRandom("Option1", "Option2", "Option3", "Option4"))

使用默认值,我可以改变其中一项的概率。我想设置所有四个项目的概率。选择Option1的概率为50%,选择Option2的比例为30%,选择Option3的比例为15%,选择Option4的比例为5%。

我想使用WeightedRandom:

代码语言:javascript
复制
    .RuleFor(c=>field, x=>PickWeightedRandom(valueArray, weightArray)

没有像PickWeightedRandom这样的方法,但WeightedRandom是随机数发生器类中的一种方法。如何让WeightedRandom正常工作?

编辑:也许是一种扩展方法?

EN

回答 2

Stack Overflow用户

发布于 2021-01-22 10:41:57

下面的方法似乎是可行的:

代码语言:javascript
复制
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;}
}

当然,使用C#扩展方法总是扩展Bogus以最好地满足您的API需求的好方法:

代码语言:javascript
复制
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);
   }
}

票数 2
EN

Stack Overflow用户

发布于 2021-01-22 03:19:13

一个答案是在其他地方选取随机字符串,然后使用=>运算符指向结果。

代码语言:javascript
复制
    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.
    }

代码语言:javascript
复制
    .RuleFor(c => c.field, _ =>
    { 
        return PickAString(values, weights); 
    }) 

这是可行的,但将其添加到库中会更优雅。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65831267

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档