2012-12-15 83 views
5

我無法弄清楚這一點。在百分數上調用隨機函數?

我需要一個解決方案來爲它的百分比調用一個隨機函數。

Ex。腳本調用subscriptions()的概率爲10%,系統調用函數「specialitems()」的概率爲3%。

我被困在這個,所以我希望有人可以幫助我與這個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(){} 

} 
?> 
+1

註釋中的百分比與實際值不匹配。爲什麼有這些評論呢? – GolezTrol

+1

只是添加作業問題,所以它可以幫助我們更好地理解你想做什麼。 –

+0

我認爲我的答案可以解決您的問題 –

回答

4

試試這個:

$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(); 

的百分比應該不會增加任何超過100。如果總和爲100下,然後剩餘的百分比是「無所作爲」。

+0

我喜歡這個解決方案,因爲它很簡單,但是它不會完全是「隨機的」,因爲它取決於機會的順序嗎? – kennypu

+1

@kennypu不,因爲'$ a'是隨機的。 – irrelephant

-1

然後用你的類和$ var名稱調用一個函數就行了。

$this->$var();