70%的时间运行JavaScript函数,从一组函数中随机选择

时间:2013-12-03 19:28:17

标签: javascript jquery arrays random

我见过How to run a randomly selected function in JavaScript?允许运行从数组中随机选择的JavaScript函数,每次都有相同的机会(例如,如果总共有两个函数,则每个函数有50%的可能性每次都要执行。)

如何编写一个函数来说明执行从函数数组中随机选择的每个函数的百分比几率? 如何进行加权随机化?

function randomFrom(array) {
    return array[Math.floor(Math.random() * array.length)];
}
var contentWrapper = function (target,type,articleId) {
  // list type ads
  if (type == 'list') {
    function randomListData() {
      var func = randomFrom([
        function () {
          fnNameA10(target, 'list');
        },
        function () {
          fnNameB20(target, 'list', articleId);
        }
      ]);
      (func)();
    }
    randomListData();
    // content type ads
  } else if (type == 'content') {
    function randomContentData() {
      var func = randomFrom([
        function () {
          fnNameA10(target, 'content');
        },
        function () {
          fnNameB20(target, 'content', articleId);
        }
      ]);
      (func)();
    }
    randomContentAd();
  }
};

2 个答案:

答案 0 :(得分:4)

Here是您的答案:

var rand = function(min, max) {
    return Math.random() * (max - min) + min;
};

var getRandomItem = function(list, weight) {
    var total_weight = weight.reduce(function (prev, cur, i, arr) {
        return prev + cur;
    });

    var random_num = rand(0, total_weight);
    var weight_sum = 0;
    //console.log(random_num)

    for (var i = 0; i < list.length; i++) {
        weight_sum += weight[i];
        weight_sum = +weight_sum.toFixed(2);

        if (random_num <= weight_sum) {
            return list[i];
        }
    }

    // end of function
};

var list = ['javascript', 'php', 'ruby', 'python'];
var weight = [0.5, 0.2, 0.2, 0.1];
var random_item = getRandomItem(list, weight);

答案 1 :(得分:3)

http://plnkr.co/edit/wzKp8PqNJ4Fmyo2504Cu?p=preview

var funcs = [
  {probability: 20, fn: function(){console.log("20%")}},
  {probability: 10, fn: function(){console.log("10%")}},
  {probability: 70, fn: function(){console.log("70%")}}
];

var total = 0;
var n = Math.random();
for(var i=0; i<funcs.length; ++i) {
  total+=funcs[i].probability;
  if(n*100<total) {
    funcs[i].fn.call(this);
    break;
  }
}

这里我得到一个介于0和1之间的随机数,然后确定该数字在数组中的位置。我这样做是通过堆叠百分比并将数字与总金额进行比较来实现的。我需要break,因为一旦条件满足,数组中的每个元素都会返回true,而我只想要第一个元素。