Skip to content

Instantly share code, notes, and snippets.

@KyleMit
Last active April 9, 2024 12:27
Show Gist options
  • Save KyleMit/74779914a806e86ecba72bcf2d915ff1 to your computer and use it in GitHub Desktop.
Save KyleMit/74779914a806e86ecba72bcf2d915ff1 to your computer and use it in GitHub Desktop.
Birthday Prize Simulation
main()
function main() {
var prizes = [-1, -1, -1, 1, 1, 2, 2, 2, 3, 3, 5, 5, 5, 5, 5, 20, 20, 20, 20, 20, 20, 40, 40, 40, 60, 100];
var simulationResults = Array.from({ length: prizes.length }, (_, i) => simulateTurns(prizes, i + 1));
console.log(simulationResults);
}
function simulateTurns(prizes, selectionCount = 15, turns = 10000) {
let winningsForAllTurns = Array.from({ length: turns }, () => simulateGame(prizes, selectionCount));
return calculateMean(winningsForAllTurns);
}
function simulateGame(prizes, selectionCount) {
let maxBusts = [...prizes].filter(num => num === -1).length;
let shuffledPrizes = shuffleArray(prizes);
let currentWinnings = 0;
let minusOneCount = 0;
for (let i = 0; i < selectionCount; i++) {
const selection = shuffledPrizes[i]
if (selection === -1) {
minusOneCount++;
currentWinnings = 0; // Lose everything if -1 is selected
if (minusOneCount === maxBusts) {
// game over
break;
}
continue;
}
currentWinnings += selection;
}
return currentWinnings
}
function shuffleArray(array) {
const shuffledArray = [...array];
for (let i = shuffledArray.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[shuffledArray[i], shuffledArray[j]] = [shuffledArray[j], shuffledArray[i]];
}
return shuffledArray;
}
function calculateMean(numbers) {
if (numbers.length === 0) { return 0; }
const sum = numbers.reduce((acc, curr) => acc + curr, 0);
const mean = sum / numbers.length;
return Math.round(mean); // simplify to whole number
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment