Page 1 of 1

Fisher-Yates shuffle

Posted: Thu Mar 18, 2021 12:20 pm
by Vegan

Code: Select all

// Fisher-Yates shuffle model
function shuffle(array) {
  	var m = array.length, t, i;
   	while (m) { // While there remain elements to shuffle ...
	    i = Math.floor(Math.random() * m--); // Pick a remaining element ...
	    t = array[m]; // And swap it with the current element...
	    array[m] = array[i];
	    array[i] = t;
	  }
  	return array;
}
This can shuffle cards, dice or any thing in a JS array

https://www.hardcoregames.ca/1998/10/25 ... s-shuffle/

I suspect that some empirical testing can be sure that the random bias is not a problem. Now that Chrome is 64-bit it's even better for card games etc.

JavaScript unlike C++ does not have an intrinsic swap function which seems obvious for this algorithm. Sorting algorithms also depend on swap as well.