I have two defined objects: x
and y
If I do following, chances of getting either x
or y
are equal – 1 of 2:
var primary = [x, y];
var secondary = primary[Math.floor(Math.random() * primary.length)];
This would take a 1 of 3 (smaller) chances of getting y
:
var primary = [x, x, y];
// secondary unchanged
etc.
But I believe, this is bad practice because if I'd wanted to set infinitesimal chances (e.g. 1 of 1e9) of getting y
, I would have to do something extremely wasteful like this:
var primary = new Array();
for (i = 1e9 - 1; i--; i) primary.push(x);
primary.push(y);
var secondary = primary[Math.floor(Math.random() * primary.length)];
Is there a better way to do this in JavaScript?
Aucun commentaire:
Enregistrer un commentaire