🐎 Implement Fisher-Yates for IList<T>.Shuffle()

Resolves #18 but leaves string.Shuffle unable to be compiled for now
This commit is contained in:
Oliver Booth 2021-01-16 14:07:49 +00:00
parent db43993d56
commit 9238459851
1 changed files with 17 additions and 38 deletions

View File

@ -56,49 +56,28 @@ namespace X10D
} }
/// <summary> /// <summary>
/// Shuffles an enumerable. /// Reorganizes the elements in a list by implementing a Fisher-Yates shuffle.
/// </summary> /// </summary>
/// <typeparam name="T">The collection type.</typeparam> /// <typeparam name="T">The element type.</typeparam>
/// <param name="source">The collection to shuffle.</param> /// <param name="source">The <see cref="IList{T}" /> to shuffle.</param>
/// <returns>Returns <paramref name="source" /> shuffled.</returns>
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source)
{
return source.Shuffle(new Random());
}
/// <summary>
/// Shuffles an enumerable.
/// </summary>
/// <typeparam name="T">The collection type.</typeparam>
/// <param name="source">The collection to shuffle.</param>
/// <param name="random">The <see cref="Random" /> instance.</param> /// <param name="random">The <see cref="Random" /> instance.</param>
/// <returns>Returns <paramref name="source" /> shuffled.</returns> public static void Shuffle<T>(this IList<T> source, System.Random? random = null)
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source, Random random)
{ {
return source.OrderBy(_ => random.Next()); if (source is null)
} {
throw new ArgumentNullException(nameof(source));
}
/// <summary> random ??= RandomExtensions.Random;
/// Shuffles a list.
/// </summary>
/// <typeparam name="T">The collection type.</typeparam>
/// <param name="source">The collection to shuffle.</param>
/// <returns>Returns <paramref name="source" /> shuffled.</returns>
public static IEnumerable<T> Shuffle<T>(this IList<T> source)
{
return source.Shuffle(new Random());
}
/// <summary> var count = source.Count;
/// Shuffles a list. while (count > 0)
/// </summary> {
/// <typeparam name="T">The collection type.</typeparam> var index = random.Next(count--);
/// <param name="source">The collection to shuffle.</param> var temp = source[count];
/// <param name="random">The <see cref="Random" /> instance.</param> source[count] = source[index];
/// <returns>Returns <paramref name="source" /> shuffled.</returns> source[index] = temp;
public static IEnumerable<T> Shuffle<T>(this IList<T> source, Random random) }
{
return source.OrderBy(_ => random.Next());
} }
} }
} }