Last active
July 19, 2023 08:22
-
-
Save Kshitij-Dhakal/8269834b83938eb88987c43310654ad6 to your computer and use it in GitHub Desktop.
Given the probability of something happening (p), and sample size (n), get a boolean such that, if the method is ran (n) number of times then you are likely to get (p*n) trues.
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
import 'dart:math'; | |
Random _random = new Random(); | |
int getRandomInt(int limit) => _random.nextInt(limit); | |
double randomDouble() => _random.nextDouble(); | |
///Given the probability of something happening (p), and sample size (n), | |
///get a boolean such that, if the method is ran (n) number of times then | |
///you are likely to get (p*n) trues. | |
/// | |
///If probability is not provided, random probability will be used | |
bool withProbabilityOfSuccess(bool b, | |
{double? probability, int sampleSize = 100}) { | |
if (!b) return false; | |
if (probability == null || probability > 1 || probability < 0) { | |
probability = randomDouble(); | |
} | |
var success = probability * sampleSize; | |
var failures = sampleSize - success; | |
var samples = List.generate(success.toInt(), (index) => true) | |
..addAll(List.generate(failures.toInt(), (index) => false)); | |
return samples[getRandomInt(sampleSize)]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment