1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Weighted Randomness

Discussion in 'PHP' started by nevetS, Jul 14, 2005.

  1. #1
    I'm putting together a script, and I would like to implement weighted randomness, I believe similar to what the co-op does.

    essentially, I have 4 items to randomly select from. I would like item 1 to have a 50% probability of being selected, item 2 to have a 25% probability of being selected, item 3 a 15% probability of being selected and item 4 a 10% chance of being selected.

    Now, I can solve this problem by making an array of 100 items and populating 1 50 times, 2 25 times, 3 15 times, and 4 10 times, but there has to be a cleaner solution. I'm not sure what the memory requirements are, but it just seems like a waste to me.

    Any ideas?
     
    nevetS, Jul 14, 2005 IP
  2. Perrow

    Perrow Well-Known Member

    Messages:
    1,306
    Likes Received:
    78
    Best Answers:
    0
    Trophy Points:
    140
    #2
    Try something like this.

    X = random number between 0 and 100
    if x < 50 then choise = 1
    else if x < 75 then choise = 2
    else if x < 90 then choise = 3
    else choise = 4
    Code (markup):
    That should do the trick.
     
    Perrow, Jul 14, 2005 IP
  3. dct

    dct Finder of cool gadgets

    Messages:
    3,132
    Likes Received:
    328
    Best Answers:
    0
    Trophy Points:
    230
    #3
    If each object has a weight can you just do $RandNo = rand(1, totalweights); and then loop through your objects until $RandNo is within that objects range
    e.g.

    Item 1 - 1 -> 10 (weight 10)
    Item 2 - 11 -> 15 (weight 5)
    Item 3 - 16 -> 18 (weight 3)
    Item 4 - 19 -> 20 (weight 2)

    I don't think I've explained this very well but hopefully you'll get the gist, if you create a 100 element array I will never speak to you again :)
     
    dct, Jul 14, 2005 IP
  4. nevetS

    nevetS Evolving Dragon

    Messages:
    2,544
    Likes Received:
    211
    Best Answers:
    0
    Trophy Points:
    135
    #4
    I am sooo stupid sometimes. thanks guys. You have no idea the complexities that I was working my way through... :D
     
    nevetS, Jul 14, 2005 IP