Skip to content

Instantly share code, notes, and snippets.

@aalmada
Created June 18, 2021 07:55
Show Gist options
  • Save aalmada/c90ab9f45263ff0540b1bb75614430ad to your computer and use it in GitHub Desktop.
Save aalmada/c90ab9f45263ff0540b1bb75614430ad to your computer and use it in GitHub Desktop.
Fisher-Yates Shuffle implemented in C#
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