Created
May 15, 2022 19:08
-
-
Save azerum/a20c1c2d58707cce54ac904ebecadb5c to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| /** | |
| * 'probabilities' is an array of pairs [probability, choice] | |
| */ | |
| function chooseWithProbabilities(probabilities) { | |
| const pSum = probabilities.reduce((sum, [p, _]) => sum + p, 0); | |
| if (pSum !== 100.0) { | |
| throw new Error( | |
| 'Sum of the probabilities must be equal to 100. ' | |
| + `Current sum is ${pSum}` | |
| ); | |
| } | |
| probabilities.sort(([p1, _], [p2, __]) => p1 - p2); | |
| //generatedP is in range [0, 100) | |
| let generatedP = Math.random() * 100; | |
| for (const [p, choice] of probabilities) { | |
| if (generatedP <= p) { | |
| return choice; | |
| } | |
| generatedP -= p; | |
| } | |
| } | |
| //Code to test the function | |
| const probabilities = [ | |
| [10, 'a'], | |
| [20, 'b'], | |
| [50, 'c'], | |
| [20, 'd'] | |
| ]; | |
| const choicesToCounts = { | |
| 'a': 0, | |
| 'b': 0, | |
| 'c': 0, | |
| 'd': 0 | |
| }; | |
| const totalExperiments = 100_000_000; | |
| for (let i = 0; i < totalExperiments; ++i) { | |
| const choice = chooseWithProbabilities(probabilities); | |
| ++choicesToCounts[choice]; | |
| } | |
| for (const [choice, count] of Object.entries(choicesToCounts)) { | |
| const p = count / totalExperiments * 100; | |
| const [expectedP, _] = probabilities.find(([_, c]) => c === choice); | |
| console.log(`${choice}: p = ${p}, expectedP = ${expectedP}`); | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ES5 version: