3

I'm generating some random x and y coordinates for a player in a game:

var xcoordRed = Math.floor((Math.random() * 790) +1); var ycoordRed = Math.floor((Math.random() * 400) +1); 

But I need to exclude from xcoordRed the range 325 - 375 and from ycoordRed 150 - 250.

How would I go about doing this efficiently?

2
  • 1
    Can you show us what have you achieve so far? Commented Apr 23, 2016 at 11:55
  • possible duplicate of Generate random number outside of range (which is in python, but highlights possible problems and has very good solutions) Commented Apr 23, 2016 at 12:11

2 Answers 2

5

Simple math, reduce the range of the random call by the difference of the excluded range, and then if the random value is bigger than the lower exclusion delimiter, just increase it by the exclusion difference. Meaning:

var diff = 375 - 325; // add 1 if inclusive var xcoordRed = Math.floor((Math.random() * (790 - diff)) +1); if (xcoordRed >= 325) xcoordRed += diff; // the same approach goes for Y 

This means that, if the random value is, say, 324, it will remain 324. But, if it's 330, it will become 380, etc. The highest possible random number, 740, will become 790, of course.


var r = document.getElementById('r'); function gen() { var diffx = 375 - 325; var diffy = 250 - 150; var xcoordRed = Math.floor((Math.random() * (790 - diffx)) + 1); if (xcoordRed >= 325) xcoordRed += diffx; var ycoordRed = Math.floor((Math.random() * (400 - diffy)) + 1); if (ycoordRed >= 150) ycoordRed += diffy; r.textContent = 'X: ' + xcoordRed + ' Y: ' + ycoordRed; }
<button onclick="gen()">Generate</button> <div id="r"></div>

Sign up to request clarification or add additional context in comments.

Comments

0

You can create an array of allowed list and get a random value from allowed range. Not sure if this is very efficient, but it can work with multiple chunks to be excluded.

function getArrayWithExcludes(min, max, exclude) { var _tmp = []; for (var i = min; i < max; i++) { if (!exclude.some(function(item) { return i > item.min && i < item.max })) _tmp.push(i); } return _tmp; } function getRandomValue(arr) { var len = arr.length; var random = Math.floor(Math.random() * len) % len; return arr[random]; } var xExRange = [{ min: 10, max: 50 }, { min: 325, max: 375 }]; var yExRange = [{ min: 150, max: 250 }]; var xRange = getArrayWithExcludes(0, 790, xExRange); var yRange = getArrayWithExcludes(0, 400, yExRange); var xcoordRed = getRandomValue(xRange); var ycoordRed = getRandomValue(yRange); document.write("<pre>" + JSON.stringify({x:xcoordRed,y: ycoordRed},0,4) + "</pre>");

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.