Jump to content

[SOLVED] Weighted Rand


MadnessRed

Recommended Posts

Hi I was wondering if there was already a function that did this. For example, Say I have 3 items, 1,2 and 3, and I had an array saying how much of each I had eg.

 

$items = array(1 => 75,

2 => 25,

3 => 0);

 

Then it would pick and random item, so there would be a 75% chance if picking item 1, 25% of picking an item 2 and % chance of picking an item 3.

 

I was wondering if there already was a function for this. if not I can make one myself easy enough.

Link to comment
https://forums.phpfreaks.com/topic/131539-solved-weighted-rand/
Share on other sites

i don't think there is a "weighted random" function like that...off the top of my head though, this should work:

<?php
  $items = array(
    1 => 75,
    2 => 25,
    3 => 0,
  );
  $list = array();
  foreach($items as $key => $weight){
    if($weight > 0) //Skip if there is no weight
      $list = array_merge($list,array_fill(0,$weight,$key)); //Add the entry $weight times
  }
  shuffle($list); //Randomize list
  print $list[0]; //Grab one
?>

Link to comment
https://forums.phpfreaks.com/topic/131539-solved-weighted-rand/#findComment-683186
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.