Random Plot

by Tonio Loewald

HTML

<h2>Random Plotter</h2>
<p>Simple canvas plot per conversation with Scott of the shuffle outcomes, treating each card as an x,y plot point where x is its position in the deck and y is its unique id.</p>
<p>It looks about as random as you'd expect. See <a href="http://www.empiricalzeal.com/2012/12/21/what-does-randomness-look-like/">this article</a> on what randomness looks like.</p>
<p>Comparing Math.random to the simple LCG implementation (included but commented out) shows some distinct non-random qualities in the LCG version (e.g. a series of vertical bands become apparent, meaning that certain positions in the deck are likely to correspond to a small range of adjacent cards).</p>

JavaScript

// Set your random function here

function RNG(seed) {
  // LCG using GCC's constants
  this.m = 0x100000000; // 2**32;
  this.a = 1103515245;
  this.c = 12345;

  this.state = seed ? seed : Math.floor(Math.random() * (this.m-1));
}
RNG.prototype.nextInt = function() {
  this.state = (this.a * this.state + this.c) % this.m;
  return this.state;
}
RNG.prototype.nextFloat = function() {
  // returns in range [0,1]
  return this.nextInt() / (this.m - 1);
}

var r = new RNG(123);

var rand = Math.random; // function(){ return r.nextFloat() };

function shuffle(){
    var i, deck = [];
    for(i = 0; i < 52; i++){
        deck.splice(Math.floor(rand() * (deck.length+1)), 0, i);
    }
    console.log(deck);
    return deck;
}

$(function(){
    var w = 52,
        h = 52,
        s = 10,
        c = $('<canvas/>').attr({width:w*s, height:h*s}).appendTo('body'),
        g = c.get(0).getContext('2d');
    
    g.fillStyle = 'rgba(0,0,0,1)';
    g.fillRect(0,0,w*s,h*s);
    g.fillStyle = 'rgba(255,255,255,0.1)';
    
    setInterval(function(){
        var i, deck;
        deck = shuffle();
        
        for(i in deck){
            g.fillRect(i*s,deck[i]*s,s,s);
        }
    }, 20);
});