Skip to content
Felipe Ribeiro edited this page May 31, 2014 · 5 revisions

Definition

The Fisher–Yates shuffle (named after Ronald Fisher and Frank Yates), also known as the Knuth shuffle (after Donald Knuth), is an algorithm for generating a random permutation of a finite set—in plain terms, for randomly shuffling the set.

Source: Wikipedia

Code: https://github.com/felipernb/algorithms.js/blob/master/algorithms/math/fisher_yates.js

Test: https://github.com/felipernb/algorithms.js/blob/master/test/algorithms/math/fisher_yates.js

How to use

var shuffle = require('algorithms').Math.fisherYates
var a = [1,2,3,4,5];
// Shuffles the array in-place
shuffle(a);
console.info(a); // [3,5,1,2,4] (or any other random permutation)

Extending native Array object

var shuffle = require('algorithms').Math.fisherYates;
Array.prototype.shuffle = function () {
  shuffle(this);
};
var a = [1,2,3,4,5];
a.shuffle();
Clone this wiki locally