Page 1 of 1

random array percent

Posted: Sun Jan 27, 2008 12:54 pm
by Sled
I was wondering if someone could help me with making a random array with percent
(random array is chosen due to a percent chance that it has)

Code: Select all

$randomdrop = "1,2,3,4,5,6";
$randomdrop2 = "10,80,50,60,30,40";
                $a = explode(",",$randomdrop);
                $b = explode(",",$randomdrop2);
                
    mt_srand((double)microtime()*1000000);  
    $k = array_keys($a);
    $r = mt_rand(0, count($k)-1);
    echo $a[$r]." %".$b[$r];
    $percent=$b[$r]/10;
    if (rand($percent,10) == 10)
    {echo $a[$r]." good!";}
 
in $randomdrop2 is the percentages. i am coding an rpg in which a monster drops an item. currently it will just pick out of a list but i would like to add some percentages to the list so we can have rare drops.

the sample code will pick a random array and then will randomly display a "good" if the percent is high enough. problem with this is i would like it to always pick a random array.

example would be
apple - common
sword - rare
the apple would have more of a chance to be chosen yet the sword can still appear.


idonno if i went on too much of an explaining rant but oh well, if anyone could help that would be awesome!!
Thanks, Sled

Re: random array percent

Posted: Sun Jan 27, 2008 1:42 pm
by JAM
Dunno how you would apply it, or if I even misunderstood your post, but here are something I thought of;

Code: Select all

 
    $randomdrop = array(1,2,3,4,5,6);
    $randomdrop2 = array(10,80,50,60,30,40);
 
    foreach ($randomdrop2 as $k => $v) {
        for ($i = 0; $i < $v; $i++) {
            $newarray[] = $randomdrop[$k];
        }
    }
    shuffle($newarray);
    echo $newarray[array_rand($newarray, 1)];
    print_r($newarray);
    print_r(array_count_values($newarray));
The math in it is not entirely correct, but I just whipped something together to demonstrate my thought. Populate an array with the item_id X number of times, shuffle the array and select an random value from it. That way, the higher $randomdrop2, the higher chance to get selected.