您的位置:首页 > 编程语言 > Java开发

JAVA权重抽取

2016-05-31 20:11 381 查看
一.在项目中要实现按照设计好的权重进行数据的不固定推送,这里贴出已经应用在项目中的算法。

二.代码

1.

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.wiimedia.mryl.userportrait.bean.CalcWeightBean;

public class CalcWeightUtil {
public  Map<String, Integer> getCalc(List<CalcWeightBean> beans){
Map<String, Integer> showMap = null;
Double sum = getSum(beans);
Double random = 0.0;
CalcWeightBean kw = null;
showMap = new LinkedHashMap<String, Integer>();
for(int i = 0; i < 7; i++) {
random = getRandom(sum);
CalcWeightBean cw = getKW(beans, random);
if(showMap.containsKey(cw.getTag())) {
showMap.put(cw.getTag(), showMap.get(cw.getTag()) + 1);
} else {
showMap.put(cw.getTag(),1);
}
}
return showMap;
}

public  CalcWeightBean getKW(List<CalcWeightBean> nodes, Double rd) {
CalcWeightBean ret = null;
int curWt = 0;
for(CalcWeightBean n : nodes){
curWt += n.getWeight();
if(curWt >= rd) {
ret = n;
break;
}
}
return ret;
}
public static Double getSum(List<CalcWeightBean> nodes) {
Double sum = 0.0;
for(CalcWeightBean n : nodes)
sum += n.getWeight();
return sum;
}
public static Double getRandom(Double seed) {
return (double)Math.round(Math.random() * seed);
}

}


2.

import java.util.Comparator;

/**
*
* @author Songjia
*
* @作用: 进行权重排序的Javabean
*
* @时间:2016-05-06 19:55
*
*/
public class CalcWeightBean implements Comparator{
private double weight;
private String tag;
public CalcWeightBean() {
super();
}
public CalcWeightBean(double weight, String tag) {
super();
this.weight = weight;
this.tag = tag;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public int compare(Object o1, Object o2) {
CalcWeightBean n1 = (CalcWeightBean)o1;
CalcWeightBean n2 = (CalcWeightBean)o2;
if(n1.weight > n2.weight)
return 1;
else
return 0;

}

}


3.测试类

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.wiimedia.mryl.userportrait.bean.CalcWeightBean;
import com.wiimedia.mryl.utils.CalcWeightUtil;

public class Weight {
public static void main(String[] args) {
CalcWeightUtil calcWeightUtil = new CalcWeightUtil();
CalcWeightBean bean1= new CalcWeightBean(31.25,"鼻炎");
CalcWeightBean bean2= new CalcWeightBean(18.75,"高血压");
CalcWeightBean bean3= new CalcWeightBean(18.75,"癌症");
CalcWeightBean bean4= new CalcWeightBean(31.25,"糖尿病");
CalcWeightBean bean5= new CalcWeightBean(31.25,"关节炎");
List<CalcWeightBean> beans = new ArrayList<CalcWeightBean>();
beans.add(bean1);
beans.add(bean2);
beans.add(bean3);
beans.add(bean4);
beans.add(bean5);

Map<String, Integer> calc = calcWeightUtil.getCalc(beans);
System.out.println(calc);
for (Map.Entry<String, Integer> entry : calc.entrySet()) {
System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 算法