Support Forums
Dice Roll Probabilities - Printable Version

+- Support Forums (https://www.supportforums.net)
+-- Forum: Categories (https://www.supportforums.net/forumdisplay.php?fid=87)
+--- Forum: Coding Support Forums (https://www.supportforums.net/forumdisplay.php?fid=18)
+---- Forum: PHP The Hypertext Preprocessor (https://www.supportforums.net/forumdisplay.php?fid=21)
+---- Thread: Dice Roll Probabilities (/showthread.php?tid=2641)



Dice Roll Probabilities - zone - 11-07-2009

Credits and Source: http://www.dreamincode.net/

Name: Dice Roll Probabilities
Description: A function which given n, m-sided dice returns an array with the probabilities of each collective score.
Snippet:

PHP Code:
function dieOdds($dieType$dieMax null$scale null$truncate null){
    if(!
is_int($dieType) || $dieType 1$dieType 1;
    if(!
is_int($dieMax) || $dieMax 1$dieMax $dieType;
    if(!
is_int($scale) || $scale 0$scale $dieType;
    if(!
is_int($truncate) || $truncate 0$truncate $dieType;
    
bcscale($scale);
    
$temp '1d' $dieType;
    
$output = array($temp => array_fill(1$dieType1));
    for(
$i 2$i <= $dieMax$i++){
        
$combinations end($output);
        
$temp $i 'd' $dieType;
        
$output[$temp] = array_fill($i$dieType $i $i 10);
        
reset($combinations);
        
$start key($combinations);
        
end($combinations);
        
$end key($combinations);
        for(
$j $start$j <= $end$j++)
            for(
$k 1$k <= $dieType$k++)
                
$output[$temp][$j $k] = bcadd($output[$temp][$j $k], $combinations[$j]);
    }
    foreach(
$output as $key => $value){
        
reset($value);
        
$start key($value);
        
end($value);
        
$end key($value);
        
$sum 0;
        
$total bcpow($dieTypesubstr($key0strpos($key'd')));
        for(
$i $end$i >= $start$i--){
            
$sum bcadd($sum$value[$i]);
            
$value[$i] = bcmul(bcmul(bcdiv($sum$total), 100), 1$truncate);
        }
        
$output[$key] = $value;
    }
    return 
$output;


Instructions: Just copy and paste this function into your code. It works with BCMath function in order to handle large probabilities such as 20d6. Returns an array.
Thankyou for reading. Be happy always Smile