开发者

how to randomize an integer variable, with odds on certain numbers appearing

To get a random whole number between 0 and 4 inclusive, I use the following code:

var random = Math.floor(Math.random() * 5);

However I want the number 4 to be chosen twice as often as the other numbers. How would I go about doing getting a random number between 0-4 inclusive, but with开发者_StackOverflow the number 4 appearing twice as many times as 0-3?


I think the easist way is to add the number twice to the array:

var nums = [0, 1, 2, 3, 4, 4];
var index = Math.floor(Math.random() * 6);
var random = nums[index];

But for something more generic, you may have a table:

var nums = [0, 1, 2, 3, 4];
var odds = [0.16667, 0.16667, 0.16667, 0.16667, 0.33333];
var r = Math.random();
var i = 0;
while(r > 0)
  r -= odds[i++];
var random = nums[i];


Just do it like this:

var random = Math.floor(Math.random() * 6);
if (random == 5) random = 4;


Is this of any use:

http://www.javascriptkit.com/javatutors/weighrandom2.shtml


Math.floor(Math.random() * 2) == 0 ? Math.floor(Math.random() * 5) : 4

Here, 4 has 50% chance coz of first random selector, adding up 20% for second random selector.


I like sje397's initial answer with the correction that Paddy is suggesting:

var nums = [0, 1, 2, 3, 4, 4];
var random = nums[Math.floor(Math.random() * 6)];


The technique behind your requirement is to use a Shuffle Bag random generator. More details: http://web.archive.org/web/20111203113141/http://kaioa.com:80/node/53

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜