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");
}
Odd array glitch. Random undefined values
Page 1 of 11 Replies - 354 Views - Last Post: 15 January 2013 - 02:17 PM
#1
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:
Replies To: Odd array glitch. Random undefined values
#2
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:
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
Page 1 of 1
|
|

New Topic/Question
Reply


MultiQuote




|