Get a random number focused on center

后端 未结 20 3039
离开以前
离开以前 2020-12-12 09:28

Is it possible to get a random number between 1-100 and keep the results mainly within the 40-60 range? I mean, it will go out of that range rarely, but I want it to be main

20条回答
  •  误落风尘
    2020-12-12 09:44

    This answer is really good. But I would like to post implementation instructions (I'm not into JavaScript, so I hope you will understand) for different situation.


    Assume you have ranges and weights for every range:

    ranges - [1, 20], [21, 40], [41, 60], [61, 100]
    weights - {1, 2, 100, 5}
    

    Initial Static Information, could be cached:

    1. Sum of all weights (108 in sample)
    2. Range selection boundaries. It basically this formula: Boundary[n] = Boundary[n - 1] + weigh[n - 1] and Boundary[0] = 0. Sample has Boundary = {0, 1, 3, 103, 108}

    Number generation:

    1. Generate random number N from range [0, Sum of all weights).
    2. for (i = 0; i < size(Boundary) && N > Boundary[i + 1]; ++i)
    3. Take ith range and generate random number in that range.

    Additional note for performance optimizations. Ranges don't have to be ordered neither ascending nor descending order, so for faster range look-up range that has highest weight should go first and one with lowest weight should go last.

提交回复
热议问题