Reputation: 13999
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 the number 4 appearing twice as many times as 0-3?
Upvotes: 0
Views: 920
Reputation: 1497
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
Upvotes: 1
Reputation: 41812
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];
Upvotes: 8
Reputation: 5666
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)];
Upvotes: 2
Reputation: 36373
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.
Upvotes: 2
Reputation: 7213
Just do it like this:
var random = Math.floor(Math.random() * 6);
if (random == 5) random = 4;
Upvotes: 4
Reputation: 21659
Is this of any use:
http://www.javascriptkit.com/javatutors/weighrandom2.shtml
Upvotes: 2