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 })``

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;
}
\$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 with..
#probability #php #node #javascript #math #random #odds Just finishing up brewing up some fresh ground comments...