From 9238459851bf9f4f6b427482547bef22f4d1e2bb Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Sat, 16 Jan 2021 14:07:49 +0000 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=8E=20Implement=20Fisher-Yates=20for?= =?UTF-8?q?=20IList.Shuffle()?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Resolves #18 but leaves string.Shuffle unable to be compiled for now --- X10D/src/ListExtensions.cs | 55 ++++++++++++-------------------------- 1 file changed, 17 insertions(+), 38 deletions(-) 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; + } } } }