generate random numbers within a range with different probabilities

前端 未结 6 1071
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-06 07:05

How can i generate a random number between A = 1 and B = 10 where each number has a different probability?

Example: number / probability

1 - 20%

2 -

6条回答
  •  北海茫月
    2020-12-06 07:24

    Build an array of 100 integers and populate it with 20 1's, 20 2's, 10 3's, 5 4's, 5 5's, etc. Then just randomly pick an item from the array.

    int[] numbers = new int[100];
    // populate the first 20 with the value '1'
    for (int i = 0; i < 20; ++i)
    {
        numbers[i] = 1;
    }
    // populate the rest of the array as desired.
    
    // To get an item:
    // Since your Rand() function returns 0 < R < 1
    int ix = (int)(Rand() * 100);
    int num = numbers[ix];
    

    This works well if the number of items is reasonably small and your precision isn't too strict. That is, if you wanted 4.375% 7's, then you'd need a much larger array.

提交回复
热议问题