Created
May 19, 2021 22:33
-
-
Save aivascu/ddd6c942f75ea0f71c9268c55517059b to your computer and use it in GitHub Desktop.
RandomFromFixedSequence example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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