Visualize random number generator

by Trevor Dixon

HTML

<h1>Kind of Normal</h1>

CSS

body { white-space: nowrap; }

.bar {
    display: inline-block;
    width: 1px;
    vertical-align: bottom;
    background-color: #3D5285;
}

JavaScript

// Generate random numbers
var max = 500,
    step = 165,
    occurrences = new Array(max);

/*
  By repeatedly getting a random number between 1 and step, it's like
  repeatedly calling C#'s Random.next() which returns an integer that is
  at most int.MaxValue.
*/
function getRandomNumber(max, step) {
    var r = 0;
    for (var i = 0; i < max; i += step) {
        r += ~~(Math.random()*step);
    }
    return r % max;
}

for (var i = 0; i < 80000; i++) {
    var r = getRandomNumber(max, step);
    occurrences[r] = occurrences[r] || 0;
    ++occurrences[r];
}

// Visualize
occurrences.forEach(function(count, i) {
    count = count || 0;
    $(document.body).append(
        $('<div class="bar"/>').css('height', count + 'px')
    );
});