Generate A Weighted Random Number

前端 未结 11 2203
予麋鹿
予麋鹿 2020-11-22 12:40

I\'m trying to devise a (good) way to choose a random number from a range of possible numbers where each number in the range is given a weight. To put it simply: given the

相关标签:
11条回答
  • 2020-11-22 12:49

    I use the following

    function weightedRandom(min, max) {
      return Math.round(max / (Math.random() * max + min));
    }
    

    This is my go-to "weighted" random, where I use an inverse function of "x" (where x is a random between min and max) to generate a weighted result, where the minimum is the most heavy element, and the maximum the lightest (least chances of getting the result)

    So basically, using weightedRandom(1, 5) means the chances of getting a 1 are higher than a 2 which are higher than a 3, which are higher than a 4, which are higher than a 5.

    Might not be useful for your use case but probably useful for people googling this same question.

    After a 100 iterations try, it gave me:

    ==================
    | Result | Times |
    ==================
    |      1 |    55 |
    |      2 |    28 |
    |      3 |     8 |
    |      4 |     7 |
    |      5 |     2 |
    ==================
    
    0 讨论(0)
  • 2020-11-22 12:49

    This one is in Mathematica, but it's easy to copy to another language, I use it in my games and it can handle decimal weights:

    weights = {0.5,1,2}; // The weights
    weights = N@weights/Total@weights // Normalize weights so that the list's sum is always 1.
    min = 0; // First min value should be 0
    max = weights[[1]]; // First max value should be the first element of the newly created weights list. Note that in Mathematica the first element has index of 1, not 0.
    random = RandomReal[]; // Generate a random float from 0 to 1;
    For[i = 1, i <= Length@weights, i++,
        If[random >= min && random < max,
            Print["Chosen index number: " <> ToString@i]
        ];
        min += weights[[i]];
        If[i == Length@weights,
            max = 1,
            max += weights[[i + 1]]
        ]
    ]
    

    (Now I'm talking with a lists first element's index equals 0) The idea behind this is that having a normalized list weights there is a chance of weights[n] to return the index n, so the distances between the min and max at step n should be weights[n]. The total distance from the minimum min (which we put it to be 0) and the maximum max is the sum of the list weights.

    The good thing behind this is that you don't append to any array or nest for loops, and that increases heavily the execution time.

    Here is the code in C# without needing to normalize the weights list and deleting some code:

    int WeightedRandom(List<float> weights) {
        float total = 0f;
        foreach (float weight in weights) {
            total += weight;
        }
    
        float max = weights [0],
        random = Random.Range(0f, total);
    
        for (int index = 0; index < weights.Count; index++) {
            if (random < max) {
                return index;
            } else if (index == weights.Count - 1) {
                return weights.Count-1;
            }
            max += weights[index+1];
        }
        return -1;
    }
    
    0 讨论(0)
  • 2020-11-22 12:50

    I have a slotmachine and I used the code below to generate random numbers. In probabilitiesSlotMachine the keys are the output in the slotmachine, and the values represent the weight.

    const probabilitiesSlotMachine         = [{0 : 1000}, {1 : 100}, {2 : 50}, {3 : 30}, {4 : 20}, {5 : 10}, {6 : 5}, {7 : 4}, {8 : 2}, {9 : 1}]
    var allSlotMachineResults              = []
    
    probabilitiesSlotMachine.forEach(function(obj, index){
        for (var key in obj){
            for (var loop = 0; loop < obj[key]; loop ++){
                allSlotMachineResults.push(key)
            }
        }
    });
    

    Now to generate a random output, I use this code:

    const random = allSlotMachineResults[Math.floor(Math.random() * allSlotMachineResults.length)]
    
    0 讨论(0)
  • 2020-11-22 12:51

    Rejection sampling (such as in your solution) is the first thing that comes to mind, whereby you build a lookup table with elements populated by their weight distribution, then pick a random location in the table and return it. As an implementation choice, I would make a higher order function which takes a spec and returns a function which returns values based on the distribution in the spec, this way you avoid having to build the table for each call. The downsides are that the algorithmic performance of building the table is linear by the number of items and there could potentially be a lot of memory usage for large specs (or those with members with very small or precise weights, e.g. {0:0.99999, 1:0.00001}). The upside is that picking a value has constant time, which might be desirable if performance is critical. In JavaScript:

    function weightedRand(spec) {
      var i, j, table=[];
      for (i in spec) {
        // The constant 10 below should be computed based on the
        // weights in the spec for a correct and optimal table size.
        // E.g. the spec {0:0.999, 1:0.001} will break this impl.
        for (j=0; j<spec[i]*10; j++) {
          table.push(i);
        }
      }
      return function() {
        return table[Math.floor(Math.random() * table.length)];
      }
    }
    var rand012 = weightedRand({0:0.8, 1:0.1, 2:0.1});
    rand012(); // random in distribution...
    

    Another strategy is to pick a random number in [0,1) and iterate over the weight specification summing the weights, if the random number is less than the sum then return the associated value. Of course, this assumes that the weights sum to one. This solution has no up-front costs but has average algorithmic performance linear by the number of entries in the spec. For example, in JavaScript:

    function weightedRand2(spec) {
      var i, sum=0, r=Math.random();
      for (i in spec) {
        sum += spec[i];
        if (r <= sum) return i;
      }
    }
    weightedRand2({0:0.8, 1:0.1, 2:0.1}); // random in distribution...
    
    0 讨论(0)
  • 2020-11-22 12:55

    Generate a random number R between 0 and 1.

    If R in [0, 0.1) -> 1

    If R in [0.1, 0.2) -> 2

    If R in [0.2, 1] -> 3

    If you can't directly get a number between 0 and 1, generate a number in a range that will produce as much precision as you want. For example, if you have the weights for

    (1, 83.7%) and (2, 16.3%), roll a number from 1 to 1000. 1-837 is a 1. 838-1000 is 2.

    0 讨论(0)
  • 2020-11-22 12:55

    How about

    int [ ] numbers = { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 , 2 } ;

    then you can randomly select from numbers and 0 will have an 80% chance, 1 10%, and 2 10%

    0 讨论(0)
提交回复
热议问题