Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call random function on percents?

Tags:

php

random

I cannot figure this out.

I need a solution to call a random function for it's percent.

Ex. there is 10% chances that the script calls subscriptions() and 3% chance that the system call the function "specialitems()".

I am stuck in this, so i hope someone can help me with this brainkiller.

<?php
   class RandomGifts {
   public $chances = '';

   public function __construct($user) {
          $this->user = $user;

          //Find percent for each function
          $this->chances = array( 
                 'subscriptions' => 10, // 10%
                 'specialitems'  => 3,  //  5%
                 'normalitems'   => 30, // 40%
                 'fuser'         => 50, // 70%
                 'giftcards'     => 7,  //  7%
          );

 //This should call the function which has been calculated.
 self::callFunction(?);

 }

   public function subscriptions(){}
   public function specialitems(){}
   public function normalitems(){}
   public function fuser(){}
   public function giftcards(){}

}
?>
like image 257
Angelena Godkin Avatar asked Oct 22 '22 22:10

Angelena Godkin


1 Answers

Try this:

$a = rand(1, 100);
$total = 0;
$f = '';
foreach($this->chances as $function => $percent) {
    $total += $percent;
    if($a <= $total) {
        $f = $function;
        break;
    }
}
if(!empty($f))
    $this->$f();

The percentages shouldn't add to anything above 100. If the sum is under 100, then the remaining percentage is "do nothing."

like image 118
irrelephant Avatar answered Nov 12 '22 21:11

irrelephant