y u no do it?

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?

Jul 14, 2005 IP
2. ### PerrowWell-Known Member

Messages:
1,306
78
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.

Jul 14, 2005 IP
3. ### dctFinder of cool gadgets

Messages:
3,134
328
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

, Jul 14, 2005 IP

Messages:
2,544