鉴于整数,例如一个列表 1,2,3,4
,我知道如何选择基于其权重的物品。的示例项目将具有10%,20%,30%和40%的概率,分别
Given a list of integers, e.g. 1, 2, 3, 4
, I know how to select items based on their weight. The example items would have probabilities of 10%, 20%, 30%, and 40%, respectively.
有没有基于其权重的逆选择项目的一个同样简单的方法?用这种方法,例如列表将等于的加权列表 1,1/2,1/3,1/4
(48%,24%,16% ,12%),但我想,以避免浮点运算的转化和利用。 (假设所有整数的是积极的,非零。)
Is there an equally simple method of selecting items based on the inverse of their weight? With this method, the example list would be equal to a weighted list of 1, 1/2, 1/3, 1/4
(48%, 24%, 16%, 12%), but I want to avoid the conversion and use of floating-point arithmetic. (Assume all of the integers are positive and non-zero.)
推荐答案
您可以划分数最不常见多通过每个号码并获得积分的地步。
You could divide the numbers' least common multiple by each number and get integral proportions.
有关 [1,2,3,4]
,这是12。你的权重为12/1 = 12,12/2 = 6,12/3 = 4,12/4 = 3。
For [1, 2, 3, 4]
, this is 12. Your weights are 12/1=12, 12/2=6, 12/3=4, 12/4=3.
您也可以乘它们放在一起,而不是与LCM打扰为好。的数字将更高,但比例将是相同的:24/1 = 24,24/2 = 12,24/3 = 8,24/4 = 6
You could also multiply them all together and not bother with the LCM as well. The numbers will be higher but the proportions will be the same: 24/1=24, 24/2=12, 24/3=8, 24/4=6.
相关推荐
最新文章