Random Distribution in Javascript

Math.random distribution

How random is random? This simple example gives a way to vizualize how random the Javascript Math.random() method distribution is. As Javascript doesn't take a random seed, the output should not repeat between browser instances.

Random Distribution in Javascript visualized

I won't go through the whole code here, just the bits that matter. First of all, our Map variable keeps track of the tiles that make up the demonstration. It also provides a generate method, that creates a new map grid of tiles. Each tile keeps track of how many times it has been hit, starting at 0, and adding 10 every time the tile is hit by the random generator. This is used to determine how light the tile is, with 0 being black and 255 being white:


var Map = {
	tiles	: [],
	width	: 60,
	height	: 40,
	
	generate : function(w, h)
	{
		this.tiles.splice(0, this.tiles.length);
		
		tileW = canvasW / w;
		tileH = canvasH / h;
		
		this.width = w;
		this.height = h;
		
		for(var i = 0; i < w*h; i++) { this.tiles.push(0); }
	}
};

Our tiles are updated with the updateCells method. This generates a random number x times, where x = [total tiles] / 10 (ie; 10% of the number of tiles). The random number generated is between 0 and last tile index, and the corresponding tile in the Map.tiles list has 10 added to its value.


function updateCells()
{
	// 10% random update
	for(var i = 0; i < (Map.width * Map.height) / 10; i++)
	{
		var idx = Math.floor(Math.random() * Map.tiles.length);
		Map.tiles[idx]+= 10;
		if(Map.tiles[idx] > 255) { Map.tiles[idx] = 255; }
	}
}

Give it a try to see the hit rate of numbers within the range 0 to [Map width] x [Map height]. If you have a better computer than mine, try changing the Map.generate(60, 40); call in the onload method to different values to see random hits over different ranges.

Page loaded in 0.017 second(s).