Reputation: 631
So I have two functions
function toWin(){
console.log('win')
}
function toLose(){
console.log('lose')
}
how do I get each functions to be executed based on the percentage given?
Say in 100 tries, toWin()
should be executed 90 times, and randomly.
I'd like to change the win_percentage
to any number any time.
var win_percentage = 90; // 90 percent
function generateResultRandomly(){
//code to execute either function should be here.
}
If there's any other way I can get this without my methods, it'll be appreciated, or you could help in writing the algorithm and I code it out.
Upvotes: 2
Views: 631
Reputation: 5539
Try this
var win_percentage = 90; // 90 percent
function generateResultRandomly(){
var random = Math.floor(Math.random() * 101); // returns a random integer from 0 to 100
if (random <= win_percentage) {
toWin();
} else {
toLose();
}
}
Upvotes: 1