# 【erlang】根据奇数位的概率随机求偶数位 概率列表求随机值

23 篇文章 3 订阅

-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)
].

%% ----------------------------------------------------
%% Func: rand_weight (T)
%% Description: 根据奇数位的概率随机求偶数位,如果概率为0则返回该Item
%% Args: 列表如:[50,a,30,b,20,c]
%% Returns:
%% ----------------------------------------------------
rand_weight(WeightList)->
case sum_odd(WeightList) of
0 ->
rand_weight(0,WeightList,[]);
OtherPerhaps ->
rand_weight(rand:uniform(OtherPerhaps),WeightList,[])
end.
%% 碰到0概率直接返回Item,不参与概率计算
rand_weight(_,[],NoPerhaps)->NoPerhaps;
rand_weight(Rand,[0,Value|List],NoPerhaps)->
rand_weight(Rand,List,[Value|NoPerhaps]);
%% 根据奇数位的概率随机求偶数位 列表如:[50,3,30,5,20,10]
rand_weight(Rand,[Perhaps,Value|T],NoPerhaps)->
if
Rand =< Perhaps -> [Value|NoPerhaps]; %% 返回[随机Value ++ 0概率Value]
true -> rand_weight(Rand-Perhaps,T,NoPerhaps)
end.

%% ----------------------------------------------------
%% Func: sum_odd (List)
%% Description: 计算奇数位的和
%% Args: [50,3,30,5,20,10]
%% Returns: 100
%% ----------------------------------------------------
sum_odd(List)->sum_odd(List,0).
sum_odd([],Sum)->Sum;
sum_odd([A,_B|List],Sum)->sum_odd(List,Sum+A).



• 0
点赞
• 0
收藏
觉得还不错? 一键收藏
• 0
评论
07-10 989
05-22 818
11-03 872
09-25 582
10-14 2012
06-25
03-20

### “相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。