Simple Way to Calculate the Odds of Something Happening

       

Here is a quick way to express a chance of something happening.

This is an example in JavaScript that gives you a 1 in 3 chance of being true.

[true, false, false].sort(function(){ return Math.random() >= 0.5 ? 1 : -1 })[0]

Basically, we populate an array w/ true and false values and select a random element.

Here is the same idea in PHP but we'll create a never ending loop so we can see it in action and print to the screen

<?php
$chance = 50; // Let's compute a 50% chance 
$true_vals = array_fill(0, $chance, true); 
$false_vals = array_fill(0, 100 - $chance, false); 
$vals = array_merge($true_vals, $false_vals); 
$tmp = [];

while(true){
    $f = [];
    foreach(range(1,count($vals)) as $i){
            shuffle($vals); // grab and use random true/false value
            $f[] = $vals[0]; 
    }
    $f = array_filter($f); // remove false values
    $c = count($f); // get count of true values
    $tmp[] = $c; 
    echo array_sum($tmp) / count($tmp) . "%\n";  
}

Here is a StackOverflow thread discussing the topic

https://stackoverflow.com/questions/11552158/percentage-chance-of-saying-something/47502706#47502706

Tagged w/ #probability #php #node #javascript #math #random #odds

Apps I've Built

PhotoLocationChanger
Easily change the location on your photos and videos
Click here for more info about the app
PhotoDateChanger
Easily change the dates and times on your photos and videos
Click here for more info about the app
VocabReminder
English dictionary with notifications so you won't forget what you're studying!
Click here for more info about the app
VocabQuiz
The app that quizzes and scores you on your vocabulary!
Click here for more info about the app