Skip to content

Instantly share code, notes, and snippets.

@congdanhqx-zz
Forked from anonymous/Shuffle
Last active December 28, 2015 21:19
Show Gist options
  • Save congdanhqx-zz/7564086 to your computer and use it in GitHub Desktop.
Save congdanhqx-zz/7564086 to your computer and use it in GitHub Desktop.
Shuffle An Array in C#
/// <summary>
/// Shuffle an <seealso cref="Array"/> of type <typeparamref name="T"/>
/// then return it for chaining.
/// </summary>
/// <typeparam name="T">Type of element in array.</typeparam>
/// <param name="array">The array which need to shuffle. This array will be modified.</param>
/// <returns>The modified array. It's the same reference with the input array.</returns>
public T[] Shuffle<T>(T[] array)
{
Random rnd = new Random();
for (int i = 0; i < array.Length; ++i)
{
int idx = rnd.Next(array.Length);
T tmp = array[i];
array[i] = array[idx];
array[idx] = tmp;
}
return array;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment