本文介绍了javascript帮助中的概率?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对不起,我是JS的新手,似乎无法弄明白:我怎么做概率?

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

我完全不知道,但我我想做点什么:100%的几率,可能有0.7%的几率执行函数 e(); 和30%的几率执行函数 d(); 等等 - 它们将为每个函数添加最多100%的不同函数,但我还没有弄清楚如何以任何形式执行此操作。

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.

我发现的大多是奇怪的高中数学教程由Javascriptkit或其他东西提供。

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

推荐答案

例如我们定义了许多函数

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])();
}

例如,让我们试试我们的3个函数,100000次尝试:

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);

我的Firefox上的结果

The result on my Firefox

a = 20039, b = 70055, c = 9906

所以 a 运行约20%, b ~70%且 c ~10%。

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


编辑以下评论。


Edit following comments.

如果您的浏览器咳嗽返回(funcs [i])(); ,只需替换funcs数组

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

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

这个新函数(字符串)

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

然后替换函数的最后一行 randexec ()

then replace the final line of the function randexec()

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

新的

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

这篇关于javascript帮助中的概率?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 16:35