Created
January 9, 2019 21:33
-
-
Save azrafe7/bc612870d5e4854c95542cc379079652 to your computer and use it in GitHub Desktop.
Fisher-Yates shuffle algorithm
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
| // 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