tags:

views:

1157

answers:

4

I know how to generate a random number in PHP but lets say I want a random number between 1-10 but I want more 3,4,5's then 8,9,10's. How is this possible? I would post what I have tried but honestly, I don't even know where to start.

+3  A: 

The naive hack for this would be to build a list or array like

1, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8, 9, 9, 10, 10

And then select randomly from that.

IainMH
Exactly right. Create a list with the numbers weighted in the proportion you want them weighted (you can use another function to create the list, if possible), and then randomly select an item from the list.
Ross
Only downside is that if you want the number 1 to be 1 trillion times more likely than the other ones, you'll need an array of 1 trillion+ elements.
Allain Lalonde
@Allain Lalonde Oh quite. It doesn't scale but it's very simple and might be enough for the OP's needs.
IainMH
+6  A: 

There's a pretty good tutorial for you.

Basically:

  1. Sum the weights of all the numbers.
  2. Pick a random number less than that
  3. subtract the weights in order until the result is negative and return that number if it is.
Allain Lalonde
Also, this does not have the memory overhead of the prior answer (build another array with the desired distribution and selected randomly from it)
Crescent Fresh
This is the non-naive hack. :-)
IainMH
+4  A: 

For an efficient random number skewed consistently towards one end of the scale:

  • Choose a continuous random number between 0..1
  • Raise to a power γ, to bias it. 1 is unweighted, lower gives more of the higher numbers and vice versa
  • Scale to desired range and round to integer

eg. in PHP (untested):

function weightedrand($min, $max, $gamma) {
    $offset= $max-$min+1;
    return floor($min+pow(lcg_value(), $gamma)*$offset);
}
echo(weightedrand(1, 10, 1.5));
bobince
I love your answer. Please take a look at my question (link below). I'd love to hear from you on expanding this. http://stackoverflow.com/questions/4030427/generate-random-weighted-value
Kevin Peno
A: 

This tutorial walks you through it, in PHP, with multiple cut and paste solutions:

http://w-shadow.com/blog/2008/12/10/fast-weighted-random-choice-in-php/

Brad Parks