2016-01-02 112 views
0

请原谅我的语言。选择概率,检查值

我选择的概率。概率之和等于1. 例如:如果我绘制了数字0-0,6,则其概率值为0,6。

我的实际代码:

<!doctype html> 
<html> 
<head> 
    <meta charset="UTF-8"> 
    <title>Probability</title> 
</head> 
<body> 

<?php 
$fruits = array(); 
$table = array(array('fruit'=>'orange', 'probability'=>0.6), array('fruit'=>'strawberry', 'probability'=>0.3),array('fruit'=>'raspberry', 'probability'=>0.1)); 

echo '<pre>'; 
echo print_r($table); 
echo '</pre>'; 

for($i=0; $i<10; $i++){ 
    $temp = rand(0,10)/10; 
    if($temp<=0.6) { 
     $fruits[$i]=$table[0]['fruit']; 
    } 
    else if($temp>0.6 && $temp<=0.9) { 
     $fruits[$i]=$table[1]['fruit']; 
    } 
    else { 
     $fruits[$i]=$table[2]['fruit']; 
    } 
} 

echo '<p>Table</p>'; 
echo '<pre>'; 
echo print_r($fruits); 
echo '</pre>'; 
?> 
</body> 
</html> 

现在我用if,但我不知道如何来自动执行它,因为最终会有更多的水果。概率值会经常变化,但现在我必须手动更改if表达式。 你如何检查数组中随机元素之间的绘制值并显示她的名字?

回答

1

从我的头顶:

$fruits = array(); 
$table = array(
    array('fruit' => 'orange', 'probability' => 60 /* percent */), 
    array('fruit' => 'strawberry', 'probability' => 30), 
    array('fruit' => 'raspberry', 'probability' => 10) 
); 

// append rand_min & rand_max values to table rows 
for($i = 0; $i < count($table); $i++) 
{ 
    $row = &$table[$i]; 

    if ($i > 0) 
    { 
    $previous_row = $table[$i - 1]; 

    $row["rand_min"] = $previous_row["rand_max"]; 
    $row["rand_max"] = $row["rand_min"] + $row["probability"]; 
    } 
    else 
    { 
    $row["rand_min"] = 0; 
    $row["rand_max"] = $row["probability"]; 
    } 

    unset($row); // to avoid side effects when $row is used later 
} 

// calculate fruits 
for($i = 0; $i < 10; $i++) 
{ 
    $rand = rand(0, 100); 

    foreach ($table as $row) 
    { 
    if ($row["rand_min"] <= $rand && $rand <= $row["rand_max"]) 
    { 
     $fruits[$i] = $row["fruit"]; 

     break; 
    } 
    } 
} 

print_r($fruits); 

的想法是遍历所有表行,而不是使用一个单一的,如果每个水果。

+0

谢谢回答。 我想这样的事情: 0-0,6 - >橙色 0,6-0,9 - >草莓 0,9-1,0 - >树莓 例如,现在如果概率= 0.7 - >橙色 我想要草莓。 – vjdj

+0

@vjdj是否允许修改表结构? – ViRuSTriNiTy

+0

你觉得这个怎么样修改:如果($行[ “概率”<= 1- $概率) – vjdj