Skip to content

Instantly share code, notes, and snippets.

@aivascu
Created May 19, 2021 22:33
Show Gist options
  • Save aivascu/ddd6c942f75ea0f71c9268c55517059b to your computer and use it in GitHub Desktop.
Save aivascu/ddd6c942f75ea0f71c9268c55517059b to your computer and use it in GitHub Desktop.
RandomFromFixedSequence example
public class RandomFromFixedSequence<T> : ICustomization
{
private IEnumerator<int> randomizer;
private List<T> sequence;
public void Customize(IFixture fixture)
{
this.sequence = fixture.CreateMany<T>().ToList();
this.randomizer = new RoundRobinSequence(0, sequence.Count - 1).GetEnumerator();
fixture.Register(PickRandomItemFromSequence);
}
private T PickRandomItemFromSequence()
{
this.randomizer.MoveNext();
var randomIndex = this.randomizer.Current;
return sequence[randomIndex];
}
}
public class RoundRobinSequence : IEnumerable<int>
{
private readonly int min;
private readonly int max;
private int current;
public RoundRobinSequence(int min, int max)
{
this.min = min;
this.max = max;
this.current = min;
}
public IEnumerator<int> GetEnumerator()
{
while (true)
{
current++;
if (current > max)
{
current = current % 2 == 0 ? min + 1 : min;
}
yield return current;
current++;
}
}
IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment