Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
149
rated 0 times [  150] [ 1]  / answers: 1 / hits: 15264  / 14 Years ago, thu, october 21, 2010, 12:00:00

Sorry, I'm new to JS and can't seem to figure this out: how would I do probability?



I have absolutely no idea, but I'd like to do something: out of 100% chance, maybe 0.7% chance to execute function e(); and 30% chance to execute function d(); and so on - they will add up to 100% exactly with a different function for each, but I haven't figured out exactly how to do this in any form.



What I found is mostly strange high school math tutorials powered by Javascriptkit or something.


More From » math

 Answers
167

For instance we define a number of functions



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


That generic function works for any number of functions, it executes it and return 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 instance, let's try with our 3 functions, 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);


The result on my Firefox



a = 20039, b = 70055, c = 9906


So a run about 20%, b ~ 70% and c ~ 10%.




Edit following comments.



If your browser has a cough with return (funcs[i])();, just replace the funcs array



var funcs = [ a, b, c ]; // the old functions array


with this new one (strings)



var funcs = [ a, b, c ]; // the new functions array


then replace the final line of the function randexec()



return (funcs[i])(); // old


with that new one



return eval(funcs[i]+'()');

[#95230] Tuesday, October 19, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaelynncherokeeg

Total Points: 697
Total Questions: 109
Total Answers: 104

Location: France
Member since Thu, Mar 18, 2021
3 Years ago
jaelynncherokeeg questions
Thu, May 27, 21, 00:00, 3 Years ago
Fri, Jan 24, 20, 00:00, 4 Years ago
Thu, Nov 14, 19, 00:00, 5 Years ago
Wed, Sep 18, 19, 00:00, 5 Years ago
;