Fisher-Yates shuffle

JavaScript and client side scripting.

Moderator: General Moderators

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

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.

JavaScript unlike C++ does not have an intrinsic swap function which seems obvious for this algorithm. Sorting algorithms also depend on swap as well.
Hardcore Games™ Legendary is the Only Way to Play™
My site is powered by LAMP
Post Reply