我正在制作一个脚本,用于处理用户单击按钮时获胜的百分比。在这个主题的帮助下 php - 获胜的机会。我使用了以下代码:
function winningChance($percentage) {
if($percentage < 1 || $percentage > 100) throw new Exception('Invalid percentage');
global $result;
if(rand(1, 100) <= $percentage) {
$result = 'won';
} else {
$result = 'lost';
}
return $result;
}
echo "you have ".winningChance(50).'!';
运行此脚本后,它会向 SQL 数据库中的$result
注册用户名/姓氏/电子邮件和名为 winner
的字段
这很好用,但是我想处理具有不同获胜机会百分比的多个奖项。
假设奖品1有20%的获胜机会,奖品2 30%几率和奖品3 50%的机会。如果我使用winningChance(20)
、winningChance(30)
、winningChance(50)
用户将有更多的获胜机会。我该如何处理它,因此,赢/输过程发生在多个奖品的同一函数中?
如果我理解正确,获胜的机会取决于价格。
function getChanceOfWinning($price)
{
$chances = array(
10 => 20,
20 => 30,
30 => 50
);
if (isset($chances[$price])) {
return $chances[$price];
}
return 0; // <-- default chance
}
function calculateWinningChance($price)
{
$chance = getChanceOfWinning($price);
$calc = rand(1, 100);
if ($calc <= $chance) {
return true;
}
return false;
}
function calculateWinningChances(array $prices)
{
$results = array();
foreach($prices as $price) {
$results[$price] = calculateWinningChance($price);
}
return $results;
}
var_dump(calculateWinningChances(array(10,20, 30,40,700)));
这个解决方案怎么样?
function roll( $iChance ) {
$iCursor = rand( 0,99 );
$aModel = array();
while ( count( $aModel ) != $iChance ) {
$iRandValue = rand( 0,99 );
if ( !in_array( $iRandValue, $aModel ) ) {
$aModel[] = $iRandValue;
}
}
return in_array( $iCursor, $aModel );
}
编辑:更多性能:
function roll( $iChance ) {
$iChance = ceil( ( $iChance > 100 ) ? 100 : (int)$iChance);
$iCursor = rand( 0, 99 );
$aModel = range( 0, 99 );
shuffle( $aModel );
return in_array( $iCursor, array_slice( $aModel, 0, $iChance ) );
}
如果我理解正确,您希望同时为每个用户进行多个获胜计算,彼此独立。有很多方法可以做到这一点。例如,修改函数,以便可以将关联数组作为参数传递。
该数组将是价格=>百分比值的映射,然后您为每对进行计算。您还需要修改数组中的结果变量,并在每次传递时将计算结果推送到其中。您还可以在此处使用关联数组来显示 price=>won/lost。遍历所有对并用结果填充结果变量后,只需返回变量即可。
根据您的最后一条评论,这是您需要的:
function winningChance($percentage) {
foreach($percentage as $p) {
if($p < 1 || $p > 100)
throw new Exception('Invalid percentage');
}
if (count($percentage) != 3)
throw new Exception('Three prizes need to be defined');
$rand = rand(1, 100); // generate the random chance only once!
if ($rand <= $percentage[0])
$result = 'won first prize';
elseif ($rand <= $percentage[1])
$result = 'won second prize';
elseif ($rand <= $percentage[2])
$result = 'won third prize';
else
$result = 'lost';
return $result;
}
并像这样调用函数:
//the array contains probability percentages for the first, second and third place respectively
$res = winningChance( array(20, 30, 50) );
echo "You have $res!";
// write $res to the db here
调整你的函数代码,比如,
instead of,
if(rand(1, 100) <= $percentage) {
$result = 'won';
} else {
$result = 'lost';
}
自
if(rand(1, 100) >= 50) {
$result = 'won third price';
} else if(rand(1, 100) >= 30) {
$result = 'won second price';
}
else if(rand(1, 100) >= 20) {
$result = 'won first price';
}
else
{
$result='lost';
}