part of this method is randomness, but part needs to be a percentage chance to return true or false. I'm thinking the best way to do this is to try to add up to 100 and if my result is 100 or greater, then I return true else false.
I know that statement alone is extremely vague so let me try to spell it out a bit more:
I have a token that gives me a 50% chance to return true and one that gives me a 25% chance to return true. I think the way I want to handle this is to use a random number generator between 1 and 100. I then add the percent chance to that number and if it's greater than or equal to 100 it returns true, otherwise it returns false.
Can anyone else think of another / better way to handle a situation like this?
Burr
returning true or false based on a percentage chance
Moderator: General Moderators
- John Cartwright
- Site Admin
- Posts: 11470
- Joined: Tue Dec 23, 2003 2:10 am
- Location: Toronto
- Contact:
If I understood you correctly, this function will pass approximately 25% of the time.
Code: Select all
<?php
$pass = 0;
$fail = 0;
$chance = 25;
function checkRandom($chance)
{
return rand(1,100) <= (int)$chance;
}
for ($x=0; $x < 100; $x++) {
if (checkRandom($chance)) $pass++;
else $fail++;
}
echo 'Passes: '. $pass .'<br>';
echo 'Fail: '. $fail;
?>Code: Select all
$tokens = array(50,25);
$total_chance_true = array_sum($tokens);
$random = rand(1,100);
if($random < $total_chance_true)
return TRUE;
else
return FALSE;Code: Select all
$tokens = array(50,25);
return (rand(1,100) < array_sum($tokens))DAMN: sniped by the `cart.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.