From 3a99111a429f99544927350ad3d265c88708632e Mon Sep 17 00:00:00 2001 From: RoosterDragon Date: Sat, 13 Feb 2016 22:19:46 +0000 Subject: [PATCH] Improve Util.Shuffle. Reduce algorithmic complexity from O(n^2) to O(n). --- OpenRA.Mods.Common/Util.cs | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/OpenRA.Mods.Common/Util.cs b/OpenRA.Mods.Common/Util.cs index ecc31f5920..d37d2d6998 100644 --- a/OpenRA.Mods.Common/Util.cs +++ b/OpenRA.Mods.Common/Util.cs @@ -77,16 +77,21 @@ namespace OpenRA.Mods.Common return WPos.Lerp(w.Map.CenterOfCell(from), w.Map.CenterOfCell(to), 1, 2); } - /* pretty crap */ public static IEnumerable Shuffle(this IEnumerable ts, MersenneTwister random) { - var items = ts.ToList(); - while (items.Count > 0) + // Fisher-Yates + var items = ts.ToArray(); + for (var i = 0; i < items.Length - 1; i++) { - var t = items.Random(random); - yield return t; - items.Remove(t); + var j = random.Next(items.Length - i); + var item = items[i + j]; + items[i + j] = items[i]; + items[i] = item; + yield return item; } + + if (items.Length > 0) + yield return items[items.Length - 1]; } static IEnumerable Neighbours(CPos c, bool allowDiagonal)