javascript - Random value generation from options with chance -


i want way pick random element array, probability of element being picked expressed percentage on each element.

the array may in json format or php array, though code has written in php. following example in json:

{     "extreme":  {         "name":   "item 1",         "chance": 1.0     },     "rare":     {         "name":   "item 2",         "chance": 9.0     },     "ordinary": {         "name":   "item 3",         "chance": 90.0     } } 

for example above, following true:

  • item 1 (extreme) should picked 1 out of 100 times
  • item 2 (rare) should picked 9 out of 100 times
  • item 3 (ordinary) should picked 90 out of 100 times

in simple words: code random picking item array or json string, setting percentage chance each item.

@mhall's solution faster.

but i'll leave mine here record:

<?php  $json_string = ' { "extreme":{     "name":"item 1",     "chance":1.0   },   "rare":{     "name":"item 2",     "chance":9.0   },   "ordinary":{     "name":"item 3",     "chance":90.0   } }';  $data = json_decode($json_string, true);  $arr = array();  // cycle through "extreme", "rare" , "ordinary" foreach($data $item){     for($i=0; $i<$item['chance']; $i++){         // add item's name array, [chance] times         array_push($arr, $item['name']);     } }  shuffle($arr); // shuffle array  $chosen_item = $arr[array_rand($arr)]; // result  echo $chosen_item;  ?> 

i did test loop, executing 50,000 times, , got these results:

'item 1' => chosen 223 times   (00.4%) 'item 2' => chosen 5133 times  (10.2%) 'item 3' => chosen 44644 times (89.2%) 

Comments

Popular posts from this blog

dns - How To Use Custom Nameserver On Free Cloudflare? -

python - Pygame screen.blit not working -

c# - Web API response xml language -