Random Histogram
Histogram for Reddit! http://www.reddit.com/r/javascript/comments/11qt9e/til_mathrandom_is_not_random_enough_for_a_raffle/
by chad
HTML
<body>
<script src="http://d3js.org/d3.v2.min.js?2.10.0"></script>
</body>
CSS
body {
font: 10px sans-serif;
}
.bar rect {
fill: steelblue;
shape-rendering: crispEdges;
}
.bar text {
fill: #fff;
}
.axis path, .axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
JavaScript
// Generate 40 random numbers between 100 and 2400
var values = []
var seed = 1;
function random() {
var x = Math.sin(seed++) * 10000;
return x - Math.floor(x);
}
function sin(seed) {
return function () {
var x = Math.sin(seed++) * 10000;
return x - Math.floor(x);
}
}
function mwc(s) {
// Multiply-with-carry: https://stackoverflow.com/a/29450606/490592
// Returns number between 0 (inclusive) and 1.0 (exclusive), like Math.random()
var mask = 0xffffffff;
var m_w = (123456789 + s) & mask;
var m_z = (987654321 - s) & mask;
return function() {
m_z = (36969 * (m_z & 65535) + (m_z >>> 16)) & mask;
m_w = (18000 * (m_w & 65535) + (m_w >>> 16)) & mask;
var result = ((m_z << 16) + (m_w & 65535)) >>> 0;
result /= 4294967296;
return result;
}
}
function m32(a) {
return function() {
var t = a += 0x6D2B79F5;
t = Math.imul(t ^ t >>> 15, t | 1);
t ^= t + Math.imul(t ^ t >>> 7, t | 61);
return ((t ^ t >>> 14) >>> 0) / 4294967296;
}
}
function hashCode(str) {
var hash = 0, i, chr;
if (str.length === 0) return hash;
for (i = 0; i < str.length; i++) {
chr = str.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
}
// MurmurHash3 string to int hash: https://stackoverflow.com/a/7616484/490592
function xmur3(str) {
for(var i = 0, h = 1779033703 ^ str.length; i < str.length; i++)
h = Math.imul(h ^ str.charCodeAt(i), 3432918353),
h = h << 13 | h >>> 19;
return function() {
h = Math.imul(h ^ h >>> 16, 2246822507);
h = Math.imul(h ^ h >>> 13, 3266489909);
return (h ^= h >>> 16) >>> 0;
}
}
BINS = 100;
NUMBERS = 10000000;
GENERATOR = random;
for (var i = 0; i < NUMBERS; i++) {
h = xmur3((i).toString())()
values.push(m32(h)());
}
// A formatter for counts.
var formatCount = d3.format(",.0f");
var margin = {top: 10, right: 30, bottom: 30, left: 30},
...