For example, we define a number of functions
function a () { return 0; } function b () { return 1; } function c () { return 2; } var probas = [ 20, 70, 10 ];
This universal function works for any number of functions, it executes it and returns the result:
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])(); }
For example, try with our 3 functions, 100,000 attempts:
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);
Result on my firefox
a = 20039, b = 70055, c = 9906
So, mileage is about 20%, b ~ 70% and c ~ 10%.
Change the following comments.
If your browser has a cough with return (funcs[i])(); just replace the funcs array
var funcs = [ a, b, c ];
with this new one (lines)
var funcs = [ "a", "b", "c" ];
then replace the end line of the randexec() function
return (funcs[i])();
with this new
return eval(funcs[i]+'()');