Created
May 9, 2018 12:17
-
-
Save phra/5e90c7a0c8012d6547806dac467ed4a0 to your computer and use it in GitHub Desktop.
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
const GREEN = 'green' | |
const YELLOW = 'yellow' | |
const RED = 'red' | |
const GREEN_WEIGHT = .2 | |
const YELLOW_WEIGHT = .3 | |
const RED_WEIGHT = .5 | |
const people = [ | |
{ user: 'user1', grade: GREEN }, | |
{ user: 'user2', grade: GREEN }, | |
{ user: 'user3', grade: GREEN }, | |
{ user: 'user4', grade: GREEN }, | |
{ user: 'user5', grade: GREEN }, | |
{ user: 'user6', grade: YELLOW }, | |
{ user: 'user7', grade: YELLOW }, | |
{ user: 'user8', grade: YELLOW }, | |
{ user: 'user9', grade: YELLOW }, | |
{ user: 'user10', grade: RED }, | |
{ user: 'user11', grade: RED }, | |
{ user: 'user12', grade: RED }, | |
{ user: 'user13', grade: RED }, | |
] | |
function chooseUser(people) { | |
const greens = people.filter(p => p.grade === GREEN) | |
const yellows = people.filter(p => p.grade === YELLOW) | |
const reds = people.filter(p => p.grade === RED) | |
const random = Math.random() | |
if (random < GREEN_WEIGHT) { | |
return greens[Math.floor(Math.random() * greens.length)] | |
} else if (random < GREEN_WEIGHT + YELLOW_WEIGHT) { | |
return yellows[Math.floor(Math.random() * yellows.length)] | |
} else { | |
return reds[Math.floor(Math.random() * reds.length)] | |
} | |
} | |
const ITERATIONS = 500 | |
let greenCounter = 0 | |
let yellowCounter = 0 | |
let redCounter = 0 | |
for (let i = 0; i < ITERATIONS; i++) { | |
switch (chooseUser(people).grade) { | |
case GREEN: | |
greenCounter++ | |
break | |
case YELLOW: | |
yellowCounter++ | |
break | |
case RED: | |
redCounter++ | |
break | |
} | |
} | |
console.log(`After ${ITERATIONS} iterations, this is the result: | |
- GREEN: #times: ${greenCounter}, actual: ${100 * greenCounter / (greenCounter + yellowCounter + redCounter)}%, expected: ${Math.round(GREEN_WEIGHT * 100)}% | |
- YELLOW: #times: ${yellowCounter}, actual: ${100 * yellowCounter / (greenCounter + yellowCounter + redCounter)}%, expected: ${Math.round(YELLOW_WEIGHT * 100)}% | |
- RED: #times: ${redCounter}, actual: ${100 * redCounter / (greenCounter + yellowCounter + redCounter)}%, expected: ${Math.round(RED_WEIGHT * 100)}% | |
`) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment