Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Methods call in random order (C#)

Tags:

c#

I want to write a C# program that executes several methods A(), B() and C() in random order. How can I do that?

like image 351
Gjorgji Avatar asked Jan 26 '11 01:01

Gjorgji


1 Answers

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());
like image 153
Timwi Avatar answered Oct 14 '22 01:10

Timwi