Last active
November 7, 2024 18:28
-
-
Save Funecio-Agrante/322a4b4b9be244048b09a25b8bfbd2b7 to your computer and use it in GitHub Desktop.
ChatGPT suggestion for implementation for finding a fixed number of rare events in a fixed number of trials
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function dynamicProbabilityDistribution(totalTrials, totalRareEvents) { | |
// Initialize remaining counts of trials and rare events | |
let remainingTrials = totalTrials; | |
let remainingRareEvents = totalRareEvents; | |
// Array to store the result of each trial | |
const results = Array(totalTrials).fill("common"); | |
// Loop over each trial | |
for (let i = 0; i < totalTrials; i++) { | |
// Calculate the probability of a rare event for the current trial | |
const probabilityOfRare = 1 - (1 - remainingRareEvents / remainingTrials); | |
// Randomly determine if the current trial yields a rare item | |
if (Math.random() < probabilityOfRare) { | |
results[i] = "rare"; | |
remainingRareEvents--; // Decrease rare event count if one is found | |
} | |
// Decrease the number of remaining trials | |
remainingTrials--; | |
// Stop early if all rare events have been distributed | |
if (remainingRareEvents === 0) { | |
break; | |
} | |
} | |
// If any rare events remain undrawn by the last few trials, | |
// fill those in the remaining trials to ensure all rare events are distributed | |
let j = totalTrials - 1; | |
while (remainingRareEvents > 0) { | |
if (results[j] === "common") { | |
results[j] = "rare"; | |
remainingRareEvents--; | |
} | |
j--; | |
} | |
return results; | |
} | |
// Example usage | |
const totalTrials = 10000; | |
const totalRareEvents = 100; | |
const results = dynamicProbabilityDistribution(totalTrials, totalRareEvents); | |
console.log(results); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment