W
W
WQP2017-01-11 16:51:04
PHP
WQP, 2017-01-11 16:51:04

Random with probability for elements?

Hello, how can I make a function that will display a random result from an array? These elements have a drop chance.

[
 {
   "id" : 1,
   "chance" : 10
 },
 {
   "id" : 20,
   "chance" : 70
 },
 {
   "id" : 34,
   "chance" : 20
 }
]

There is one theory. Create a temporary array of 100 elements and duplicate id [1...1, 20 .... 20, 34 .... 34] there. But I don't think this is the best solution. Tell me please

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya Karavaev, 2017-01-11
@WQP

Sea of ​​solutions. Depends on your imagination.
I would do this:
1. Calculate the current drop chance, something like this mt_rand(0, 10000) / 100.
2. Filter the array to remove elements with a chance lower than step 1.
3. Run array_shuffle, for example.
4. Select the desired number of elements.
If the chance is needed for each element to count separately, then accordingly it happens during filtering. Fortunately, there is filtering with a callback: php.net/manual/ru/function.array-filter.php

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question