I want to write a C# program that executes several methods A(), B() and C() in random order. How can I do that?
Assuming a random number generator declared like this:
public static Random Rnd = new Random();
Let’s define a Shuffle
function to bring a list into random order:
/// <summary>
/// Brings the elements of the given list into a random order
/// </summary>
/// <typeparam name="T">Type of elements in the list.</typeparam>
/// <param name="list">List to shuffle.</param>
/// <returns>The list operated on.</returns>
public static IList<T> Shuffle<T>(this IList<T> list)
{
if (list == null)
throw new ArgumentNullException("list");
for (int j = list.Count; j >= 1; j--)
{
int item = Rnd.Next(0, j);
if (item < j - 1)
{
var t = list[item];
list[item] = list[j - 1];
list[j - 1] = t;
}
}
return list;
}
This Shuffle implementation courtesy of romkyns!
Now simply put the methods in a list, shuffle, then run them:
var list = new List<Action> { A, B, C };
list.Shuffle();
list.ForEach(method => method());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With