David
David

Reputation: 13999

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 the number 4 appearing twice as many times as 0-3?

Upvotes: 0

Views: 920

Answers (6)

instcode
instcode

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

sje397
sje397

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

Manfred
Manfred

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

simplyharsh
simplyharsh

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

JochenJung
JochenJung

Reputation: 7213

Just do it like this:

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

Upvotes: 4

Mike
Mike

Reputation: 21659

Is this of any use:

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

Upvotes: 2

Related Questions