jeudi 10 mai 2018

Javascript execute function by random percentage chances

lets say, I would like to trigger a function by percentage chance

function A () { console.log('A triggered'); } //50% chance to trigger

if (Math.random() >= 0.5) A();

now i would like to add in more function to be trigger by chances, what i did was

//method 1
function B () { console.log('B triggered'); } //10% chance to trigger
function C () { console.log('C triggered'); } //10% chance to trigger

if (Math.random() >= 0.5) {
    A();
} else if (Math.random() > (0.5 + 0.1)) {
    B();
} else if (Math.random() > (0.5 + 0.1 + 0.1)) {
    C();
}

But this make A() get priority before B() and C(). Therefore I change the code into

//method 2
var randNumber = Math.random();

if (randNumber <= 0.5) { A(); }
else if (randNumber > 0.5 && randNumber <= (0.5 + 0.1)) { B(); }
else if (randNumber > (0.5 + 0.1) && randNumber <= (0.5 + 0.1 + 0.1)) { C(); }

This method looks fair but it looks inefficient because it need to be hardcoded and if I have a list long of function and triggering chances, I will need to make the if else very long and messy

Question is is there any method I can done this better and efficient? unlike these 2 method i shown above.

*also fair and square is important as well (sound like a game)

Sorry if I explain the situation badly, Any help to this will be appreciated. Thanks.




Aucun commentaire:

Enregistrer un commentaire