var probs = [];
var n;
var n_init;
var t;
var max_flips;

function fact(x) {
       if(x == 0) {
           return 1;
       }
       if(x < 0 ) {
           return undefined;
       }
       for(var i = x; --i; ) {
           x *= i;
       }
       return x;
}

function render_text(t, x, y){
  textSize(64);
  text(t.toString(), x, y);
}

function setup(){
  
  createCanvas(720,300);
  n_init = 0;
  n= n_init;
  t=0;
  max_flips = 128;
 
}

function draw(){
  
  
  
  if(t%10 == 0){
    
    background(200);
    
    // calculate prob distribution for each n
    for(var i=0;i<=n;i++){
      var prob = fact(n)/(Math.pow(2,n)*fact(i)*fact(n-i));
      if(prob > 0.00001){
        probs.push(prob);
      }
    }
    
    var m = probs.length;
    for(var i=0;i<m;i++){
      fill(55);
      noStroke();
      rect(100 + (100/m) + 10*i, 250, 8, -35*m*probs[i]);
    }

    if (n < max_flips){
      n = n + 1;
    }
    else{
      n= n_init;
      t=-1;
    }
    render_text(n, 500, 80);


    probs = [];
  }
  t+=1;
  if(t > 1000000){ t = 0; }
  
}
Rerun