Coder Social home page Coder Social logo

knuth-shuffle's Introduction

knuth-shuffle

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

'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

<script src="https://raw.github.com/coolaj86/knuth-shuffle/master/index.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(b);
}());

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(b);
}());

knuth-shuffle's People

Watchers

John Shearer avatar James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.