Basically I am creating a grid and plotting points on it, and no two points can be on the exact same place [(3,4) is different than (4,3)]. The y coordinates have to be within 2 and 7 (so 2, 3, 4, 5, 6, 7) and x coordinates have to be within 1 and 7. I have a getRandom function (which can be seen below) which generates a random number between a min and max range. Here is what I have so far.
var xposition = []; var yposition = []; var yShouldBeDifferentThan = [] function placeRandom() { for (s=0; s<xposition.length ; s++ ) { if (xposition[s] == x) { // loops through all numbers in xposition and sees if the generated x is similar to an existing x yShouldBeDifferentThan.push(yposition[s]); //puts the corresponding y coordinate into an array. for (r=0; r<yShouldBeDifferentThan.length; r++) { while (y == yShouldBeDifferentThan[r]) { y = getRandom(2,7); } } } } xposition.push(x); yposition.push(y); } The problem with this is, if
xposition = [1, 5, 5, 7, 5, 5] yposition = [1, 3, 7, 2, 3, 6] yShouldBeDifferentThan = [3, 7, 3, 6] First, it will generate a random number different thah 3, say 6. Then (I think) it will see: 6 == 7? It doesn't. 6 == 3? It doesn't. 6 == 6? It does, so generate a random number different than 6. This is where the problem comes, it might generate the number 3. My getRandom function is the following:
function getRandom(min, max) { return min + Math.floor(Math.random() * (max - min + 1)); } I was thinking making the getRandom function such that I can exclude numbers as well if I want, but I don't know how to do this. If I can get it to exclude numbers, than in the last while loop of the placeRandom function, maybe I can do something like:
y = getRandom(2,7) // excluding all numbers which already exist in the ShouldBeDifferentThan array Also, note that I cannot use the indexOf method since I am using Internet Explorer 8.