knuth-shuffle
The Fisher-Yates (aka Knuth) shuffle for Browser and Node.js
- Mike Bostock's Fisher–Yates Shuffle Visualization
- How to randomize/shuffle a JavaScript array
- Fisher-Yates Shuffle on Wikipedia
- Doing the Microsoft Shuffle: Algorithm Fail in Browser Ballot
- knuth-shuffle on NPM
'nuf said.
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 even IEEE floating point math can't 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
{ 'use strict'; var a = 2113742; var b; // The shuffle modifies the original array // calling a.slice(0) creates a copy, which is assigned to b b = window; console;};
Node Example
Decentralized Install
npm install --save git+https://git.coolaj86.com/coolaj86/knuth-shuffle.js.git#v1.0
Centralized Install
npm install --save knuth-shuffle@1.0
{ 'use strict'; var shuffle = knuthShuffle; var a = 2113742; var b; // The shuffle modifies the original array // calling a.slice(0) creates a copy, which is assigned to b b = ; console;};