How to generate a random weighted distribution of elements

前端 未结 4 347
执笔经年
执笔经年 2021-01-13 07:04

I would like to return an array which has a set of unique elements randomly distributed according to custom frequency. My real world use-case is the repetition of carousel i

4条回答
  •  悲哀的现实
    2021-01-13 07:09

    C will appear eight times more often than D; D will appear 5 times less often than B; A will appear three times less often than C.

    You can do that with a weighted array of your elements:

    var elems = ["A", "B", "C", "D"];
    var weights = [2, 5, 8, 1]; // weight of each element above
    var totalWeight = weights.reduce(add, 0); // get total weight (in this case, 16)
    
    function add(a, b) { return a + b; } // helper function
    
    var weighedElems = [];
    var currentElem = 0;
    while (currentElem < elems.length) {
      for (i = 0; i < weights[currentElem]; i++)
        weighedElems[weighedElems.length] = elems[currentElem];
      currentElem++;
    }
    
    console.log(weighedElems);
    

    This will produce an array like

    ["A", "A", "B", "B", "B", "B", "B", "C", "C", "C", "C", "C", "C", "C", "C", "D"]

    so you can choose randomly from that like so

    var rnd = Math.floor(Math.random() * totalWeight);
    console.log(weighedElems[rnd]);
    

    Resources:

    • Generate A Weighted Random Number
    • Weighted random number generation in Javascript
    • Algorithm for generating weighed random numbers

提交回复
热议问题