From 1e0990fe6a62fe86d99dd6e199c7b9ba683cb6d2 Mon Sep 17 00:00:00 2001 From: "Nuno \"Omega Leo\" Diogo" Date: Sat, 25 Jan 2025 22:55:53 +0000 Subject: [PATCH] Added a new shuffle method for lists --- .../Extensions/IListExtensions.cs | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/OmegaLeo.HelperLib/Extensions/IListExtensions.cs b/OmegaLeo.HelperLib/Extensions/IListExtensions.cs index ff19214..b0801e9 100644 --- a/OmegaLeo.HelperLib/Extensions/IListExtensions.cs +++ b/OmegaLeo.HelperLib/Extensions/IListExtensions.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Security.Cryptography; namespace GameDevLibrary.Extensions { @@ -117,5 +118,28 @@ namespace GameDevLibrary.Extensions { return array[currentIndex++ % array.Count]; } + + /// + /// Shuffle around items in a list. + /// Code obtained from https://stackoverflow.com/a/1262619 + /// + /// + /// + public static void Shuffle(this IList list) + { + RNGCryptoServiceProvider provider = new RNGCryptoServiceProvider(); + int n = list.Count; + while (n > 1) + { + byte[] box = new byte[1]; + do provider.GetBytes(box); + while (!(box[0] < n * (Byte.MaxValue / n))); + int k = (box[0] % n); + n--; + (list[k], list[n]) = (list[n], list[k]); + } + } + + } } \ No newline at end of file