Jump to content

A difficult PHP question - how select from a weighted array


Recommended Posts

This may be a bizarre questions so please let me know if I can help clarify anything.

 

I have an array that contains an id, a name, and 3 values.

 

Similar to this:

 

1, apple, 0, 0, 1

2, pear, 1, 2, 3

3, pumpkin, 0, 0, 0

4, peach, 5, 9, 0

 

I need to select a random fruit (apple, pear, pumpkin, or peach) but the selection should be based on the values afterwards.

 

I.E. apple has 0 + 0 + 1 for a total of 1.

pear has 1 + 2 + 3 for a total of 6.

pumpkin has 0 + 0 + 0 for a total of 0.

peach has 5 + 9 + 0 for a total of 14.

 

Every fruit should have at least a small chance of being selected so to be safe I add 1 to all the values so I now have a list like this:

apple: 2

pear: 7

pumpkin: 1

peach: 15

 

So now I create a list like this:

 

apple

apple

pear

pear

pear

pear

pear

pear

pear

pumpkin

peach

peach

peach

peach

peach

peach

peach

peach

peach

peach

peach

peach

peach

peach

peach

 

And with this list I select 1 random entry.

 

This allows the fruit with the higher values to be selected more often, but every one has at least a slight chance of being selected.

 

Now, there absolutely must be a better was of performing this and still keep the same base chance for selection.

 

Please help.

 

How can I do this better?

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.