Prisoner's Thingy With Graph
by asemahle
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.4/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vis/4.17.0/vis.js"></script>
<div id="app">
<div>
Max Prisoners: <input type="number" v-model.number="maxPrisoners">
</div>
<button @click="reset">Resimulate</button>
<p>Running simulation with up to {{ maxPrisoners }} prisoners: </p>
<div id="visualization"></div>
</div>
JavaScript
new Vue({
el: '#app',
data: {
graph3d: null,
data: null,
maxPrisoners: 50,
stepSize: 1,
numSimulationsPerStep: 100,
graphOptions: {
width: '500px',
height: '552px',
style: 'surface',
showPerspective: true,
showGrid: true,
showShadow: false,
keepAspectRatio: true,
verticalRatio: 0.5
}
},
methods: {
reset() { },
populateData() {
// Create and populate a data table.
this.data = new vis.DataSet();
let counter = 0;
for (let numPrisoners = 0; numPrisoners < this.maxPrisoners; numPrisoners += this.stepSize){
for (let numTries = 0; numTries < this.maxPrisoners; numTries += this.stepSize) {
let successes = 0;
for (let i = 0; i < this.numSimulationsPerStep; i++) {
successes += this.runSimulation(numPrisoners, numTries);
}
this.data.add({
id: counter++,
x: numTries,
y: numPrisoners,
z: successes/this.numSimulationsPerStep,
value: successes/this.numSimulationsPerStep
});
}
}
// Instantiate our graph object.
let container = document.getElementById('visualization');
this.graph3d = new vis.Graph3d(container, this.data, this.options);
},
runSimulation(numPrisoners, numTries) {
let success = true;
// create and randomize the drawers
let drawers = [];
for (let i = 0; i < numPrisoners; i++) drawers.push(i);
drawers = _.shuffle(drawers);
// run the sim (each prisoner GO GO GO!)
for (let prisonerNumber = 0; prisonerNumber < numPrisoners; prisonerNumber++) {
// start with drawer equivalent to the prisoner's number
let selection = drawers[prisonerNumber];
// do the algorithm. Prisoner has already opened one drawer
let triesRemaining = numTries - 1;
while (triesRemaining > 0) {
...