Par exemple on définit un certain nombre de fonctions
function a() { return 0; }
function b() { return 1; }
function c() { return 2; }
var probas = [ 20, 70, 10 ]; // 20%, 70% and 10%
var funcs = [ a, b, c ]; // the functions array
Cette fonction générique fonctionne pour un certain nombre de fonctions, il l'exécute et renvoie le résultat:
function randexec()
{
var ar = [];
var i,sum = 0;
// that following initialization loop could be done only once above that
// randexec() function, we let it here for clarity
for (i=0 ; i<probas.length-1 ; i++) // notice the '-1'
{
sum += (probas[i]/100.0);
ar[i] = sum;
}
// Then we get a random number and finds where it sits inside the probabilities
// defined earlier
var r = Math.random(); // returns [0,1]
for (i=0 ; i<ar.length && r>=ar[i] ; i++) ;
// Finally execute the function and return its result
return (funcs[i])();
}
Par exemple, nous allons essayer avec nos 3 fonctions, 100000: tries
var count = [ 0, 0, 0 ];
for (var i=0 ; i<100000 ; i++)
{
count[randexec()]++;
}
var s = '';
var f = [ "a", "b", "c" ];
for (var i=0 ; i<3 ; i++)
s += (s ? ', ':'') + f[i] + ' = ' + count[i];
alert(s);
Le résultat sur mon Firefox
a = 20039, b = 70055, c = 9906
Alors une course environ 20%, b ~ 70% et c ~ 10%.
Éditez après les commentaires.
Si votre navigateur a une toux avec return (funcs[i])();
, il suffit de remplacer le tableau funcs
var funcs = [ a, b, c ]; // the old functions array
avec ce nouveau (cordes)
var funcs = [ "a", "b", "c" ]; // the new functions array
puis remplacer la dernière ligne de la fonction randexec()
return (funcs[i])(); // old
avec ce nouveau
return eval(funcs[i]+'()');
sont ces probabilités définies? comme dans, allez-vous avoir une table des probabilités qui lient à des fonctions? ou sont-ils dynamiques, basés sur l'entrée? –
La probabilité est définie, avec une table liée à la fonction. – jen