diff --git a/X10D/src/ListExtensions.cs b/X10D/src/ListExtensions.cs index 1e620e8..92ee7be 100644 --- a/X10D/src/ListExtensions.cs +++ b/X10D/src/ListExtensions.cs @@ -56,49 +56,28 @@ namespace X10D } /// - /// Shuffles an enumerable. + /// Reorganizes the elements in a list by implementing a Fisher-Yates shuffle. /// - /// The collection type. - /// The collection to shuffle. - /// Returns shuffled. - public static IEnumerable Shuffle(this IEnumerable source) - { - return source.Shuffle(new Random()); - } - - /// - /// Shuffles an enumerable. - /// - /// The collection type. - /// The collection to shuffle. + /// The element type. + /// The to shuffle. /// The instance. - /// Returns shuffled. - public static IEnumerable Shuffle(this IEnumerable source, Random random) + public static void Shuffle(this IList source, System.Random? random = null) { - return source.OrderBy(_ => random.Next()); - } + if (source is null) + { + throw new ArgumentNullException(nameof(source)); + } - /// - /// Shuffles a list. - /// - /// The collection type. - /// The collection to shuffle. - /// Returns shuffled. - public static IEnumerable Shuffle(this IList source) - { - return source.Shuffle(new Random()); - } + random ??= RandomExtensions.Random; - /// - /// Shuffles a list. - /// - /// The collection type. - /// The collection to shuffle. - /// The instance. - /// Returns shuffled. - public static IEnumerable Shuffle(this IList 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; + } } } }