记录一个工作中遇到的小问题,奇数位是概率,偶数位是数值,给一个列表根据概率求数值。列表如:[50,3,30,5,20,10]
比如50%的概率返回3,30%的概率返回5,20%的概率返回10
-module(t).
-export([
test/0,
rand_weight/1
]).
test()->
WeightList = [50,3,30,5,20,10],
[
"RandWeight:",rand_weight(WeightList),
"Rand:1",rand_weight(1,WeightList),"Rand:50",rand_weight(50,WeightList),
"Rand:51",rand_weight(51,WeightList),"Rand:80",rand_weight(80,WeightList),
"Rand:81",rand_weight(81,WeightList),"Rand:100",rand_weight(100,WeightList)
].
%% 根据奇数位的概率随机求偶数位 列表如:[50,3,30,5,20,10]
rand_weight(WeightList)->
OddSum = lists:sum([X || X <- WeightList,X rem 2 == 1]),
RandNum = rand:uniform(OddSum),
rand_weight(RandNum,WeightList).
%% 根据奇数位的概率随机求偶数位 列表如:[50,3,30,5,20,10]
rand_weight(Rand,[Perhaps,Value|T])->
if
Rand =< Perhaps -> Value;
true -> rand_weight(Rand-Perhaps,T)
end.
思路:先把奇数和加起来,然后随机1个数Rand在范围 [1,奇数和] ,然后 Rand 依次减去奇数位的概率,减不动了就是最终的范围。