perfect egg hatching odds
perfect egg hatching odds
by yairamon
HTML
<center>
<h2>How many perfect eggs might trainers hatch?</h2>
<table border="1" width="55%">
<tr>
<th>How many trainers?</th>
<td>
<input type="text" id="trainersSimulated" value="10000" />
</td>
</tr>
<tr>
<th>How many egg hatched each?</th>
<td>
<input type="text" id="trialsPerTrainer" value="2031" />
</td>
</tr>
</table>
<input type="button" id="button" value="Simulate!" />
</center>
<div id="histo" class="histo"></div>
<div id="console"> </div>
<script src="https://d3js.org/d3.v2.min.js?2.10.0">
CSS
input {
text-align: right;
}
.debug {
color: black;
}
.error {
color: red;
}
.info {
color: gray;
}
.histo {
font: 12px sans-serif;
}
body {
font: 15px courier;
}
.bar rect {
fill: steelblue;
shape-rendering: crispEdges;
}
p {
line-height: 40%;
}
.bar text {
fill: #fff;
}
JavaScript
$('#button').click(function() {
runSimulations();
});
function runSimulations() {
simulate($('#trialsPerTrainer').val(),
$('#trainersSimulated').val(),
);
}
var console = function() {
var log = function(message, type) {
switch (type) {
case 0:
strMessage = "<p class=\"debug\">" + message + "</p>";
break;
case 1:
strMessage = "<p class=\"error\">" + message + "</p>";
break;
case 2:
strMessage = "<p class=\"info\">" + message + "</p>";
break;
default:
strMessage = "<p class=\"debug\">" + message + "</p>";
}
$("#console").append(strMessage);
};
return {
log: log
};
}();
function simulate(trialsPerTrainer, trainersSimulated) {
$("#console").empty();
$("#histo").empty();
results = {};
values = [];
function dieRoll() {
return Math.ceil(6 * Math.random());
}
//console.log("Simulating...");
for (i = 0; i < trainersSimulated; i++) {
perfectCount = 0;
for (j = 0; j < trialsPerTrainer; j++) {
if (dieRoll() == 6 && dieRoll() == 6 && dieRoll() == 6)
perfectCount++;
}
if (!(perfectCount in results))
results[perfectCount] = 1.0;
else
results[perfectCount]++;
values.push(perfectCount);
}
var leftPad = (s, c, n) => c.repeat(n - s.length) + s;
var pctFormatter = new Intl.NumberFormat('en-US', {
style: 'percent',
minimumFractionDigits: 2,
});
console.log("Results:");
for (key in results) {
console.log(
leftPad(key, " ", 12) +
leftPad(pctFormatter.format(results[key] / trainersSimulated), " ", 10)
);
}
// Visual Histogram...
// A formatter for counts.
var formatCount = d3.format(",.0f");
var margin = {
top: 10,
right: 30,
bottom: 30,
left: 30
},
width = 800 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x = d3.scale.linear()
.domain([0, 25])
...