1
0
mirror of https://github.com/oliverbooth/X10D synced 2024-11-22 19:18:46 +00:00

🐎 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

View File

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