Skip to content

Instantly share code, notes, and snippets.

@omgwtfgames
Last active June 18, 2016 06:24
Show Gist options
  • Save omgwtfgames/f30db4f0ca92de00b1a7 to your computer and use it in GitHub Desktop.
Save omgwtfgames/f30db4f0ca92de00b1a7 to your computer and use it in GitHub Desktop.
Extension methods to shuffle a list in place, or return a random item
using System;
using System.Collections;
using System.Collections.Generic;
public static class ShuffleListExtensions {
/// <summary>
/// Shuffle the list in place using the Fisher-Yates method.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
public static void Shuffle<T>(this IList<T> list)
{
Random rng = new Random();
int n = list.Count;
while (n > 1) {
n--;
int k = rng.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
/// <summary>
/// Return a random item from the list.
/// Sampling with replacement.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <returns></returns>
public static T RandomItem<T>(this IList<T> list)
{
if (list.Count == 0) throw new System.IndexOutOfRangeException("Cannot select a random item from an empty list");
return list[UnityEngine.Random.Range(0, list.Count)];
}
/// <summary>
/// Removes a random item from the list, returning that item.
/// Sampling without replacement.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <returns></returns>
public static T RemoveRandom<T>(this IList<T> list)
{
if (list.Count == 0) throw new System.IndexOutOfRangeException("Cannot remove a random item from an empty list");
int index = UnityEngine.Random.Range(0, list.Count);
T item = list[index];
list.RemoveAt(index);
return item;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment