Created
June 18, 2021 07:55
-
-
Save aalmada/c90ab9f45263ff0540b1bb75614430ad to your computer and use it in GitHub Desktop.
Fisher-Yates Shuffle implemented in C#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Runtime.InteropServices; | |
namespace NetFabric | |
{ | |
public static class ShuffleExtensions | |
{ | |
public static void Shuffle<T>(this List<T> source) | |
=> Shuffle(source, new Random()); | |
public static void Shuffle<T>(this List<T> source, Random random) | |
=> Shuffle(CollectionsMarshal.AsSpan(source), random); | |
public static void Shuffle<T>(this Span<T> source) | |
=> Shuffle(source, new Random()); | |
public static void Shuffle<T>(this Span<T> source, Random random) | |
{ | |
if (source.Length < 2) | |
return; | |
for (var currentIndex = 0; currentIndex < source.Length; currentIndex++) | |
{ | |
var swapIndex = random.Next(currentIndex, source.Length); | |
if (swapIndex != currentIndex) | |
(source[swapIndex], source[currentIndex]) = (source[currentIndex], source[swapIndex]); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment