Java code
public class TEST {
public static void main(String[] args) {
List<Ad> 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);
}
public static int getAd(List<Ad> list){ //根据权重返回对应id的方法
int sumWeight = 0; //得到总权重
for(Ad ad :list){
sumWeight+=ad.getWeight();
}
Random rand = new Random();
int x = Int(sumWeight) + 1; //生成随机数
int start = 0; int end = 0;
for(int i=1;i<list.size();i++){
//计算各个权重对应的起止数值段
if(i==1){
start = (i-1).getWeight();
end = (i-1).getWeight()+(i).getWeight();
}else{
start = end;
end = (i).getWeight();
}
//根据随机数落入的范围返回对应几率的广告id
if(x>start && x<=end){
(i).getId();
}else if(x<=start){
(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) {
java生成随机数的方法this.id = id;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论