使用 Bogus 生成随机年龄身高体重

Generate Random Age Height Weight using Bogus

使用Bogus我们可以轻松生成假数据和随机数据:https://github.com/bchavez/Bogus 现在我需要生成一些 Person 的。他们有 ageweightheight,所以这是我的代码:

internal class Person
{
    public int Age { get; set; }
    public int Height { get; set; }
    public int Weight { get; set; }

    public static Faker<Person> FakeData { get; } =
        new Faker<Person>()
            .RuleFor(p => p.Age, f => f.Random.Number(8, 90))
            .RuleFor(p => p.Height, f => f.Random.Number(70, 200))
            .RuleFor(p => p.Weight, f => f.Random.Number(15, 200));
}

它会很好地生成假数据和随机数据。但有一个问题。我需要让它有条件。例如,它将生成一个年龄为 9 且身高为 180 的人!!! 或者身高70体重190的人。我需要避免这样的generationgs。

有什么解决方法吗?

要使身高限制取决于年龄,体重限制取决于身高(因此,另一个函数),您需要引用当前的 Person 实例 - 请参阅 (f, x) => { return ...} 下面的部分。

看完Generating Test Data with Bogus后,我想到了这个:

using Bogus;

namespace SO70976495
{
    public class Person
    {
        public int Age { get; set; }
        public int Height { get; set; }
        public int Weight { get; set; }

        //TODO: Put the rand declaration somewhere more sensible.
        private static Random rand = new Random();

        public static Faker<Person> FakeData
        {
            get
            {
                return new Faker<Person>()
                      .RuleFor(p => p.Age, f => f.Random.Number(8, 90))
                      .RuleFor(p => p.Height, (f, x) =>
                      {
                          return RandHeightForAge(x.Age);
                      })
                      .RuleFor(p => p.Weight, (f, x) =>
                      {
                          return RandWeightForHeight(x.Height);
                      });
            }
        }

        private static int RandHeightForAge(int age)
        {
            //TODO: Make a realistic distribution
            return rand.Next(70, (int)(70 + age / 90.0 * 130));
        }

        private static int RandWeightForHeight(int height)
        {
            //TODO: Make a realistic distribution
            return 10 * rand.Next((int)Math.Sqrt(height - 15), (int)Math.Sqrt(height + 20));
        }

        public override string ToString()
        {
            return $"Person: {Age} yrs, {Height} cm, {Weight} kg";
        }

    }
}

上面代码中的任何愚蠢之处都是我的错。