I can not realize the chance of a random house. For example:

Candy = 50% that falls out at randomness.

Chocolate = 20% that will fall at randomness.

How to realize that the chance was taken into account at random? Another example:

Sausage = 100% that will fall out at the randomness - this means when the randomness is 100%, the sausage will fall out. How to implement?

  • Do you have a code in oop style? - Rochfort
  • And what does the question have to do with MySQL? - Mike

2 answers 2

You can try this option (it is possible to make a random for several items at once):

function loot($items) { $sum = 0; $total_weight = 100; $chance = rand(1, $total_weight); foreach($items as $item => $weight) { $sum += $weight; if($sum >= $chance) { return $item; } } return "Nothing"; } print(loot(["candy"=>50])); print(loot(["chocolate"=>20])); print(loot(["wurst"=>100])); print(loot(["a"=>50,"b"=>50])); 
  • one
    The name of the function is chosen well)) - AK
  • one
    "there is an opportunity to do a random for several items at once," but only one item can return - Sergey Semushin
  • @ SemushinSergey Well, yes. If you want to fall either A or B - then see the last example. Or you can randomly separate them (as the first three examples) - br3t
  • @ SemushinSergey, there is no recursion if you think about it. A is placed in the range of a random house 1-50, B - at 51-100 - br3t
  • @ SemushinSergey, made a demo on js jsfiddle.net/br3t/7waf2d86 , the algorithm did not change - br3t

Hmm, I can suggest you use if-else, as an option . For example, rand is from 1 to 10.

 $chance = rand(1,10); if($chance == 1 or $chance == 2){ echo $chocolate; }else if($chance >= 3 and $chance <= 5){ echo $candy; } 

And so on.

  • thanks for the help. but elseif = a lot when you have to use .. - Kohl