Handlebars-Net / Handlebars.Net.Helpers

Handlebars.Net helpers in the categories: 'Boolean', 'Constants', 'Enumerable', 'Environment', 'Math', 'Regex', 'String', 'DateTime' and 'Url'.
MIT License
40 stars 15 forks source link

Random number generation isn't very random #41

Closed johngallardo closed 1 year ago

johngallardo commented 2 years ago

Consider a template spec:

{
    "time": "{{Now}}",
    "temperature": {{Random Type="Integer" Min=20 Max=100}}
}

And generation of data in a loop:

            var handlebarsContext = HandlebarsDotNet.Handlebars.Create();
            HandlebarsHelpers.Register(handlebarsContext, options => { options.UseCategoryPrefix = false; });

            var template = handlebarsContext.Compile(spec);
            for (int i = 0; i < 100; i++)
            {
                var result = template(new { });
                Console.WriteLine(result);
            }

The randomly generated data rarely varies. Seems the root cause here is the usage of RandomDataGenerator creates a new Randomizer object on every iteration of generation. The result is not much randomness, as the different Randomizer's all seem to be initialized with a seed that is based on system clock.

johngallardo commented 2 years ago

Note from RandomDataGenerator:

https://github.com/StefH/RandomDataGenerator/blob/master/src/RandomDataGenerator/Generators/RandomThingsGenerator.cs

using System;

namespace RandomDataGenerator.Generators
{
    internal class RandomThingsGenerator<T>
    {
        private readonly RandomValueGenerator _randomValueGenerator;
        private readonly T _min;
        private readonly T _max;

        public RandomThingsGenerator(T min, T max, int? seed)
        {
            _min = min;
            _max = max;
            _randomValueGenerator = new RandomValueGenerator(seed ?? Environment.TickCount);
        }

        public T Generate()
        {
            return _randomValueGenerator.Next(_min, _max);
        }
    }
}
StefH commented 1 year ago

@johngallardo This issue is solved by https://github.com/StefH/RandomDataGenerator/pull/26

A new version from Handlebars.Net.Helpers will be released shortly.