Skip to content

Instantly share code, notes, and snippets.

@azrafe7
Created January 9, 2019 21:33
Show Gist options
  • Select an option

  • Save azrafe7/bc612870d5e4854c95542cc379079652 to your computer and use it in GitHub Desktop.

Select an option

Save azrafe7/bc612870d5e4854c95542cc379079652 to your computer and use it in GitHub Desktop.
Fisher-Yates shuffle algorithm
// https://try.haxe.org/#2C0EE
// https://en.wikipedia.org/wiki/Fisher–Yates_shuffle
static public inline function swap<T>(a:Array<T>, i:Int, j:Int):Void
{
var tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
static public function shuffle<T>(a:Array<T>):Void
{
var len = a.length;
for (i in 0...len - 1) {
var j = i + Std.random(len - i);
swap(a, i, j);
}
}
// shuffle range [lo-hi)
static public function shuffleRange<T>(a:Array<T>, lo:Int, hi:Int):Void
{
var len = hi - lo;
for (i in 0...len - 1) {
var j = i + Std.random(len - i);
swap(a, lo + i, lo + j);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment