Hatchling Hatchling - 8 months ago 85
jQuery Question

How to set probability of something happens based on variable

I wonder how to set probability of something happens based on a variable.
Let's say:



var a = "5235235";
var b = "5235235";
var rand = Math.random();
if (rand < 0.3) {
console.log("30% chance");
} else {
console.log("70% chance");
}





I have tried the percentage chances like so, but I don't really know how to set for example 70% chance of something happened if variable a is equal to variable b. Any ideas?

Answer Source

Use a variable to hold the percentage, instead of hard-coding it, then assign it depending on the condition.

var pct = 0.3;
if (a == b) {
    pct = 0.7;
}
var rand = Math.random();
if (rand < pct) {
    console.log("Success!");
} else {
    console.log("Failure. :(");
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download