权重值设置问题
一个简单的方法根据权重,按照比例随机显示对应的广告, 权重值越大,概率越大。 比如有个广告list,广告属性有id,weight,写个通用方法来根据权重显示广告id:
public
class
TEST {
`
public`static
void
main(String[] args) {
`
List`new
ArrayList<Ad>();
`
list.add(`new
Ad(
1
,
5
));
`
list.add(`new
Ad(
2
,
10
));
`
list.add(`new
Ad(
3
,
20
));
`
list.add(`new
Ad(
4
,
30
));
`
list.add(`new
Ad(
5
,
35
));
`
ComTest com =`new
ComTest();
`
Collections.sort(list,com);`//对list中广告的权重要先排序,否则无法将随机数顺序安置到对应的区间
`
int`id1=
0
;
`
int`id2=
0
;
`
int`id3=
0
;
`
int`id4=
0
;
`
int`id5=
0
;
`
for`(
int
i =
0
; i <
100
; i++) {
`
int`id = getAd(list);
`
if`(id==
1
) id1++;
`
if`(id==
2
) id2++;
`
if`(id==
3
) id3++;
`
if`(id==
4
) id4++;
`
if`(id==
5
) id5++;
`
} //`
`
System.out.println(`"12345:"
+id1+
"|"
+id2+
"|"
+id3+
"|"
+id4+
"|"
+id5); //统计各id出现的次数
`
}`
`
public`static
int
getAd(List<Ad> list){
//根据权重返回对应id的方法
`
int`sumWeight =
0
;
//得到总权重
`
for`(Ad ad :list){
`
sumWeight+=ad.getWeight();`
`
}`
`
Random rand =`new
Random();
`
int`x = rand.nextInt(sumWeight) +
1
;
//生成随机数
`
int`start =
0
;
int
end =
0
;
`
for`(
int
i=
1
;i<list.size();i++){
`
//计算各个权重对应的起止数值段`
`
if`(i==
1
){
`
start = list.get(i-`1
).getWeight();
`
end = list.get(i-`1
).getWeight()+list.get(i).getWeight();
`
}`else
{
`
start = end;`
`
end = start+list.get(i).getWeight();`
`
}`
`
//根据随机数落入的范围返回对应几率的广告id`
`
if`(x>start && x<=end){
`
return`list.get(i).getId();
`
}`else
if
(x<=start){
`
return`list.get(i-
1
).getId();
`
}`else
{
`
continue`;
`
}`
`
}`
`
return`0
;
`
}`
}
``
class
Ad{
``
`
public`Ad(
int
id,
int
weight){
`
this`.id = id;
`
this`.weight = weight;
`
}`
`
int`id;
`
int`weight;
``
`
public`int
getId() {
`
return`id;
`
}`
``
`
public`void
setId(
int
id) {
`
this`.id = id;
`
}`
``
`
public`int
getWeight() {
`
return`weight;
`
}`
``
`
public`void
setWeight(
int
weight) {
`
this`.weight = weight;
`
}`
``
}
还没有评论,来说两句吧...