Skip to content

Instantly share code, notes, and snippets.

@PJensen
Created September 20, 2010 16:50
Show Gist options
  • Save PJensen/588207 to your computer and use it in GitHub Desktop.
Save PJensen/588207 to your computer and use it in GitHub Desktop.
Similar to Pythons Random-choice but for C#
/// <summary>
/// RandomChoice
/// <example>
/// <code>
/// var flowerColor = Dice.RandomChoice<Colour>(new List<Colour>()
/// {
/// new Colour(ConsoleColor.Magenta, ConsoleColor.Green),
/// new Colour(ConsoleColor.Red, ConsoleColor.Green),
/// new Colour(ConsoleColor.Yellow, ConsoleColor.Green),
/// new Colour(ConsoleColor.DarkMagenta, ConsoleColor.Green),
/// });
/// </code>
/// </example>
/// <remarks>Not dissimilar to Pythons random choice.</remarks>
/// </summary>
/// <typeparam name="T">The type of the object to return for
/// the random choice.</typeparam>
/// <param name="obj">The object that will be used to get a random element from.</param>
/// <returns>A "randomly" selected element from the list.</returns>
public static T RandomChoice<T>(IList<T> obj)
{
return obj[R.Random.Next(0, obj.Count)];
}
[Obsolete("This is an older version, from some time ago.")]
/// <summary>
/// Static class for doing something similar to Pythons random choice.
/// <remarks>This static class is not nessisarily thread safe.</remarks>
/// </summary>
/// <typeparam name="T"></typeparam>
public static class RandomChoice<T> where T: object
{
/// <summary>
/// Get the next random choice.
/// </summary>
/// <param name="aList">The list to get random choices from.</param>
/// <returns>A randomly selected element from the list.</returns>
public static T Next(IList<T> aList)
{
lock (aList)
{
return (T)aList[_random.Next(0, aList.Count)];
}
}
/// <summary>
/// Random number generator initialized with ticks.
/// <remarks>Cast to int may force negative seed.</remarks>
/// </summary>
private static Random _random =
new Random((int)DateTime.Now.Ticks);
}
@exallium
Copy link

My favourite random choice function was always:

def random_choice():
    return 4

@PJensen
Copy link
Author

PJensen commented Jul 21, 2011

That is an excellent PRNG too.

@PJensen
Copy link
Author

PJensen commented Jul 21, 2011

No but really, despite not having a lib call for random-choice, building this one wasn't too bad. The olde one was kind of a piece, I think I had lock in there to prevent the case when another thread modifies the collection while we're returning an random index from that collection. Imagine if [12] suddenly disappeared, "Object reference not set to an instance of an object." or "Index out of bounds", Maybe lock should be back in there, i'll have to double check the docs on lock.

    public static T RandomChoice<T>(IList<T> obj) { return obj[R.Random.Next(0, obj.Count)]; }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment