12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- using System;
- namespace TBL.CSharp.Utilities.Random
- {
- /// <summary>
- /// 随机数扩展工具类
- /// </summary>
- public static class Random
- {
- /// <summary>
- /// 生成非负随机数
- /// </summary>
- public static int Next(this IRandom random) => Math.Abs(Math.Max(random.NextRaw(), int.MinValue + 1));
- /// <summary>
- /// 生成随机数,并将结果取余到范围内
- /// </summary>
- /// <param name="random">随机数发生器</param>
- /// <param name="minValue">随机最小值(结果包含)</param>
- /// <param name="maxValue">随机最大值(结果不包含)</param>
- /// <returns>生成结果</returns>
- /// <exception cref="ArgumentOutOfRangeException">范围上下界不正确</exception>
- public static int Next(this IRandom random, int minValue, int maxValue)
- {
- if (minValue >= maxValue)
- throw new ArgumentOutOfRangeException(nameof(minValue),
- $"{nameof(minValue)}({minValue}) >= {nameof(maxValue)}({maxValue})");
- return minValue + random.Next() % (maxValue - minValue);
- }
- /// <summary>
- /// 生成 <c>0</c> ~ <paramref name="maxValue"/> 内随机数
- /// </summary>
- /// <param name="random">随机数发生器</param>
- /// <param name="maxValue">随机最大值(结果不包含)</param>
- /// <returns>生成结果</returns>
- /// <exception cref="ArgumentOutOfRangeException">范围上下界不正确</exception>
- public static int Next(this IRandom random, int maxValue) => random.Next(0, maxValue);
- /// <summary>
- /// 进行概率取模检定
- /// </summary>
- /// <param name="random">随机数发生器</param>
- /// <param name="minValue">随机最小值(结果包含)</param>
- /// <param name="maxValue">随机最大值(结果不包含)</param>
- /// <param name="line">检定分界线</param>
- /// <returns>随机结果对 <paramref name="line"/> 的取模值</returns>
- public static int CheckModule(this IRandom random, int minValue, int maxValue, int line) =>
- random.Next(minValue, maxValue) % line;
- /// <summary>
- /// 以百分比进行概率取模检定
- /// </summary>
- /// <param name="random">随机数发生器</param>
- /// <param name="line">检定分界线</param>
- /// <returns>在范围 <c>0</c> ~ <c>100</c> 中生成的随机结果对 <paramref name="line"/> 的取模值</returns>
- public static int CheckModulePercent(this IRandom random, int line) =>
- random.CheckModule(0, 100, line);
- /// <summary>
- /// 进行概率检定
- /// </summary>
- /// <param name="random">随机数发生器</param>
- /// <param name="minValue">随机最小值(结果包含)</param>
- /// <param name="maxValue">随机最大值(结果不包含)</param>
- /// <param name="line">检定分界线</param>
- /// <returns>随机结果是否小于 <paramref name="line"/></returns>
- public static bool Check(this IRandom random, int minValue, int maxValue, int line) =>
- random.Next(minValue, maxValue) < line;
- /// <summary>
- /// 以百分比进行概率检定
- /// </summary>
- /// <param name="random">随机数发生器</param>
- /// <param name="line">检定分界百分比</param>
- /// <returns>在范围 <c>0</c> ~ <c>100</c> 中生成的随机结果是否小于 <paramref name="line"/></returns>
- public static bool CheckPercent(this IRandom random, int line) => random.Check(0, 100, line);
- }
- }
|