The Fisher-Yates (aka Knuth) shuffle for Browser JavaScript and Node.js
Go to file
AJ ONeal ca51f5ca88 updated README 2013-12-03 01:37:35 -06:00
.gitignore Initial commit 2013-12-02 23:37:01 -08:00
LICENSE Initial commit 2013-12-02 23:37:01 -08:00
README.md updated README 2013-12-03 01:37:35 -06:00

README.md

knuth-shuffle

The Fisher-Yates (aka Knuth) shuffle for Browser and Node.js

The Fisher-Yates (Knuth) Shuffle

As Microsoft learned the hard way (see article below), function random() { return 0.5 - Math.random() } turns out to be no-so-random at all.

The fisher-yates shuffle is an algorithm so simple that not even IEEE floating point math can screw it up!

I put this on npm as knuth-shuffle because fisher-yates-shuffle was just too long of a name and shuffle was already taken.

Browser Example

<script src="./knuth-shuffle.js"></script>
(function () {
  'use strict';

  var a = [2,11,37,42]
    , b
    ;

  // The shuffle modifies the original array
  // calling a.slice(0) creates a copy, which is assigned to b
  b = window.knuthShuffle(a.slice(0));
  console.log();
});

Node Example

npm install -S knuth-shuffle
(function () {
  'use strict';

  var shuffle = require('knuth-shuffle').knuthShuffle
    , a = [2,11,37,42]
    , b
    ;

  // The shuffle modifies the original array
  // calling a.slice(0) creates a copy, which is assigned to b
  b = shuffle(a.slice(0));
  console.log();
});

See Also