views:

61

answers:

6

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?

+1  A: 

Is this of any use:

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

Mike
+5  A: 

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];
sje397
You don't actually use the nums array?
Paddy
It should be obvious the random variable returns the index of the nums array?
Tom Gullen
Thanks, Tom :).
sje397
You should change the line to: var random = nums[Math.floor(Math.random() * 6)]; for clarity
Tom Gullen
Snap...........
sje397
I wont be happy to define fixed number array, to get random numbers. Take getting twice chances for a number as a concept, as anyway you can't get exactly twice chances of a number, until you start counting their occurrence manually. And if i had to count anyhow, whats the use of randomness ??
simplyharsh
@simplyharsh: I have no idea what you mean
sje397
+3  A: 

Just do it like this:

var random = Math.floor(Math.random() * 6);
if (random == 5) random = 4;
JochenJung
+1  A: 
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.

simplyharsh
That's not twice as often as the other numbers..?
sje397
+1  A: 

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)];
John
A: 

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

instcode
+1 Would be nice if there was a `Collections.shuffle` in javascript :)
sje397