Skip to content

Instantly share code, notes, and snippets.

@mvaldesdeleon
Created November 25, 2022 16:51
Show Gist options
  • Save mvaldesdeleon/f646ed012e9c8e245d5d3423f8ff9d59 to your computer and use it in GitHub Desktop.
Save mvaldesdeleon/f646ed012e9c8e245d5d3423f8ff9d59 to your computer and use it in GitHub Desktop.
Just some world cup simulations...
let currentScores = {
'arg': 0,
'mex': 1,
'pol': 1,
'ara': 3
}
function updateScores(scores, {home, away, result}) {
scores = {...scores}
switch (result) {
case 0:
scores[home] += 1
scores[away] += 1
break;
case 1:
scores[home] += 3
break;
case -1:
scores[away] += 3
break;
}
return scores
}
let nextMatches = [
{home: 'arg', away: 'mex'},
{home: 'pol', away: 'ara'},
{home: 'mex', away: 'ara'},
{home: 'pol', away: 'arg'}
]
function randomize(match) {
return {...match, result: Math.floor(Math.random() * 3) - 1}
}
function randomizeAll(matches) {
return matches.map(randomize)
}
function summarizeScores(scores, matches) {
return matches.reduce(updateScores, scores)
}
function randomizeScores(scores, matches) {
return summarizeScores(scores, randomizeAll(matches))
}
function whoClassified(scores) {
return Object.entries(scores)
.sort(([, scoreA],[, scoreB]) => scoreB - scoreA)
.slice(0, 2)
.map(([team]) => team)
}
function didWeMakeIt(scores) {
return whoClassified(scores).includes('arg')
}
function monteCarlo() {
let runs = 10000
let yay = 0
for (let i = 0; i < runs; i++) {
let finalScores = randomizeScores(currentScores, nextMatches)
if (didWeMakeIt(finalScores)) {
yay++
}
}
return yay / runs * 100
}
function assignResults(matches, results) {
return matches.map((match, index) => ({...match, result: results[index]}))
}
function exploreAll() {
let runs = 0
let yay = 0
for (let a = -1; a < 2; a++) {
for (let b = -1; b < 2; b++) {
for (let c = -1; c < 2; c++) {
for (let d = -1; d < 2; d++) {
let finalScores = summarizeScores(currentScores, assignResults(nextMatches, [a, b, c, d]))
if (didWeMakeIt(finalScores)) {
yay++
}
runs++
}
}
}
}
return yay / runs * 100
}
let expectedValue = exploreAll()
let n = 100
let mse = Array.from(Array(n)).map(_ => (expectedValue - monteCarlo()) ** 2).reduce((a, b) => a + b, 0) / n
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment