Skip to content

Instantly share code, notes, and snippets.

@Kshitij-Dhakal
Last active July 19, 2023 08:22
Show Gist options
  • Save Kshitij-Dhakal/8269834b83938eb88987c43310654ad6 to your computer and use it in GitHub Desktop.
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.
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