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?
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>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments