Fisher-Yates shuffle

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
User avatar
Vegan
Forum Regular
Posts: 564
Joined: Fri Sep 05, 2008 3:34 pm
Location: Victoria, BC

Fisher-Yates shuffle

Post 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.
Hardcore Games™ Legendary is the Only Way to Play™
Post Reply