1 Replies - 547 Views - Last Post: 15 January 2013 - 02:17 PM

#1 njgmoorman  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 65
  • Joined: 02-October 12

Odd array glitch. Random undefined values

Posted 15 January 2013 - 01:37 PM

I've got an array that is helping me fill another array with random, non-repeating numbers. What it does is fill the first array depending on a variable assigned earlier in the program. That part works. Then, it is supposed to pick a random index from that array, push its value into the new array, then delete that value from the first array and continue to do that until the for loop has reached another value set earlier. That part works less fine. The second array is getting filled and values are being removed from the first array, but some random spots in the second array are showing up as undefined in firebug. I have no clue what is causing this. Here's the function in question:

function genMines() {
	var index;
	var tds = table.getElementsByTagName("td");
	indarr = [];
	indeces = [];
	var mineTDS = [];
	for(i=0, n; n = tds[i]; i++) {
		mineTDS.push(n);
	}
	var mineCount;
	for (mineCount=0;mineCount<mines;mineCount++) {
		for (var o = 0;o<(hw*hw);o++) {
			/*do {
				index = Math.floor(Math.random()*((hw*hw)-1) + 0);
				checkIndex();
			}
			while (indarr.length<mines);*/
			indeces.push(o);
		}
		for (var q = 0;q<mines;q++) {
			index = Math.floor(Math.random()*(hw*hw) + 0);
			indarr.push(indeces[index]);
			indeces.splice(index, 1);
		}
		var cIndex;
		for (var cntr = 0;cntr<mines;cntr++) {
			cIndex = indarr[cntr];
			mineTDS[cIndex].onclick = function() {
				gameOver();
			};
			var bomb = document.createElement("img");
			bomb.style.display = "none";
			bomb.setAttribute("src", "mine.png");
			mineTDS[cIndex].appendChild(bomb);
			indarr.splice(cIndex, 1);
			//tds[index].onclick = gameOver;
			//tds[index].className = (tdClass + " mined");
		}
	}
	imgs = table.getElementsByTagName("img");
}


Is This A Good Question/Topic? 0
  • +

Replies To: Odd array glitch. Random undefined values

#2 NathanMullenax  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 83
  • View blog
  • Posts: 176
  • Joined: 23-September 12

Re: Odd array glitch. Random undefined values

Posted 15 January 2013 - 02:17 PM

Line 21 looks suspect: it's generating indeces that are 0..hw^2-1. It should only generate an index that is between 0 and indeces.length-1, otherwise you will get undefined values.

This function will remove and return a random element from an array:
var removeRandom = function(arr){ 
    return arr.splice( Math.floor(Math.random()*arr.length),1); 
}

This post has been edited by NathanMullenax: 15 January 2013 - 02:22 PM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1