// A Yahtzee simulation
$GAMES = 1000;
if (array_key_exists('numtrials', $_POST)
&& is_numeric($_POST['numtrials'])) {
$GAMES = max(1, $_POST['numtrials']);
$GAMES = min(10000, $GAMES);
}
$num_rolls = 100;
if (array_key_exists('num_rolls', $_POST)
&& is_numeric($_POST['num_rolls'])) {
// need at least 1 die
$num_rolls = max(1, $_POST['num_rolls']);
// ensure it's something reasonable
$num_rolls = min(10000, $num_rolls);
}
$num_sides = 100;
if (array_key_exists('num_sides', $_POST)
&& is_numeric($_POST['num_sides'])) {
// need at least 1 side
$num_sides = max(1, $_POST['num_sides']);
// ensure it's something reasonable
$num_sides = min(1000, $num_sides);
}
$numprintlines = 1;
if (array_key_exists('numprintlines', $_POST)
&& is_numeric($_POST['numprintlines'])) {
$numprintlines = max(1, $_POST['numprintlines']);
}
$results = array();
$results = array_pad($results, $num_sides, 0);
$total_sum = 0;
?>
A Random Number Generator Simulation with trials
mt_srand((float)microtime()*1000000);
function roll() {
global $num_sides;
return mt_rand(1,$num_sides);
}
function printGames ($start, $numGames) {
global $results;
// if we've requested x games, but less are left
if ($start + $numGames > count($results)) {
// print out however many we can
$numGames = count($results) - $start;
}
// rough error checking
if ($start < 0 ||
$start > count($results) ||
$numGames < 1) {
return;
}
if ($numGames == 1) {
echo "
\n";
echo "
".($start+1)."
\n";
echo "
".$results[$start]."
\n";
echo "
\n";
return;
}
// print out multiple games at a time
$tempSum = 0;
for ($i = 0; $i < $numGames; $i++) {
$tempSum += $results[$start + $i];
}
echo "
\n";
echo "
".($start+1)." - ".($start+$numGames)."
\n";
echo "
".$tempSum."
\n";
echo "
\n";
return;
}
for ($g = 0; $g < $GAMES; $g++) {
$temp_sum = 0;
for ($i = 0; $i < $num_rolls; $i++) {
$temp_sum += roll();
}
$temp_average = round($temp_sum/$num_rolls, 0);
$total_sum += $temp_sum;
$results[$temp_average]++;
} // for each game
// Calculate the overall average
?>
The overall average of all the rolls was
NAN.