/*

	For more information, visit http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life

*/

var rows = 8;
var cell = new Array(rows);
var iterations = 0;

function RunConwayTest() {

	//Populate array with random values (0 or 1 -- dead or alive cells)
	for (var x=0;x<=rows;x++) {
		cell[x] = new Array(rows);
		for (var y=0;y<=rows;y++) {
			cell[x][y] = Math.floor((Math.random()) * 2); //1 or 0
		}
	}
	
	iterations = 0;
	var startTime = new Date();

	var now = new Date();
	while (now.getTime()-startTime.getTime()<LengthPerTest) {
		RunConwayCycle();
		iterations +=1;
		now = new Date();
	}
	var adjustedLength;
	adjustedLength = iterations/(now.getTime()-startTime.getTime());
	
	return adjustedLength;
}

function RunConwayCycle() {
	//Make a temporary array representing the current state of the cell array
	var newCell = new Array(rows);
	for (var x=0;x<=rows;x++) {
		newCell[x] = new Array(rows);
		for (var y=0;y<=rows;y++) {
			newCell[x][y] = cell[x][y];
		}
	}

	//Cycle through each cell in the array, count the neighbors, and determine if it needs to die/revive/no change
	for (x=0;x<=rows;x++) {
		for (y=0;y<=rows;y++) {
		
			var cnt=0; //Calc neighbor count
			var offX, offY; //offsets
			
			for(offX=-1;offX<=1;offX++) {
				for(offY=-1;offY<=1;offY++) {
				
					var curX = x+offX;
					var curY = y+offY;
					
					//curX and curY must be valid...
					var valid = true;
					if ((curX<0) || (curX>rows)) { valid = false; } //out of bounds
					if ((curY<0) || (curY>rows)) { valid = false; } //out of bounds
					if ((curX==x) && (curY==y)) { valid = false; } //can't count itself
					
					if (valid) {
						var curCell = cell[curX][curY]
						cnt += curCell;
					}
				}
			}
			
			if (cell[x][y] == 0) { //dead cell
				if (cnt==3) { newCell[x][y]=1; }
			}
			else { //alive cell
				if (cnt<2) { newCell[x][y]=0; }
				//Cells with cnt=2 or 3 survive
				if (cnt>3) { newCell[x][y]=0; }
			}
		}
	}
	
	//Change the original cell array to represent the new dead/alive cell values
	for (var x=0;x<=rows;x++) {
		for (var y=0;y<=rows;y++) {
			cell[x][y] = newCell[x][y];
		}
	}
}