12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- using System;
- using System.Collections.Generic;
- namespace TBL.CSharp.Utilities.Random.Generator
- {
- /// <summary>
- /// 已知序列的随机数生成器
- /// <para>用于固定结果的演出教学等特殊用途</para>
- /// </summary>
- public class KnownSeriesGenerator : IRandom<KnownSeriesGenerator.Seed>
- {
- /// <summary>
- /// 已经生成的随机数计数
- /// </summary>
- private long _numberGenerated;
- /// <summary>
- /// 已知序列
- /// </summary>
- private readonly Queue<int> _series;
- /// <summary>
- /// 构造
- /// </summary>
- /// <param name="series">已知序列</param>
- /// <exception cref="ArgumentNullException">已知序列为空</exception>
- public KnownSeriesGenerator(params int[] series)
- {
- if (series == null)
- throw new ArgumentNullException(nameof(series));
- _series = new Queue<int>();
- foreach (var num in series)
- _series.Enqueue(num);
- }
- public int NextRaw()
- {
- var num = _series.Dequeue();
- _series.Enqueue(num);
- ++_numberGenerated;
- return num;
- }
- public Seed DumpSeed() => new Seed(_numberGenerated, _series);
- public void RestoreBySeed(Seed seed)
- {
- _series.Clear();
- foreach (var num in seed.KnownSeries)
- _series.Enqueue(num);
- _numberGenerated = seed.NumberGenerated;
- }
- /// <summary>
- /// 种子
- /// </summary>
- public readonly struct Seed
- {
- /// <summary>
- /// 已经生成的随机数计数
- /// </summary>
- public readonly long NumberGenerated;
- /// <summary>
- /// 已知序列
- /// </summary>
- public readonly int[] KnownSeries;
- /// <summary>
- /// 构造
- /// </summary>
- public Seed(long numberGenerated, Queue<int> knownSeries)
- {
- NumberGenerated = numberGenerated;
- KnownSeries = knownSeries.ToArray();
- }
- }
- }
- }
|