lundi 23 novembre 2015

Generate random coordinates (excluding some specific ones)

I have a multidimensional array, which I'm using as a very simple coordinate system. To generate random coordinates, I came up with this very simple function:

var coords = [
  [1,0,0,1,0,0,0,0,1,0,0,0,1,1,0,1,1,1,1,1,1,1,0,1],
  [0,0,0,1,1,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,1],
  [1,0,1,1,1,1,1,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,1],
  [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,1,1],
  [1,1,1,0,1,1,0,0,1,1,0,1,1,1,1,1,1,0,0,1,1,0,1,1],
  [1,1,1,0,1,1,0,0,1,1,0,1,1,1,1,0,0,0,0,1,1,0,1,1],
  [0,0,0,0,1,1,0,0,1,1,0,1,1,1,1,0,0,1,0,1,1,0,1,1],
  [1,0,1,0,1,1,1,1,0,0,0,1,1,1,0,0,0,1,0,1,1,0,1,1]
];

function getRandomInt( min, max ) {
  return Math.floor( Math.random() * (max - min + 1) ) + min;
}

function randomCoords() {
  var x, y;

  do {
    x = getRandomInt( 0, coords[ 0 ].length - 1 );
    y = getRandomInt( 0, coords.length - 1 );
  } 
  while ( coords[ y ][ x ] !== 1 );

  return [ x, y ];
}

As you might see, I only want to get random coordinates that are 1 in my array. Although this is working, I was wondering if there's a better / more effective way to do it? Sometimes (especially if there are lots of 0s in my coordinate system) it takes a bit to return a value. In that time (as far as I know) javascript can't do anything else... so everything will just pause...




Aucun commentaire:

Enregistrer un commentaire