1. 需求分析
今天接到老大给的一个任务,让我做一个从一些流量中,按照模版进行采样。需要按照等比例和均分。
例如:
模版有A和B,总数量是10个,A有4个,B有6个。
假设现在需要采5个:
如果按照等比例分配:那么A要采2个,B要才3个。
假设现在需要采6个:
按照均分,A和B个才3个。
理想情况下,如果都是上面的这种当然好了,能够整除。但是很多情况下是不能整除的,但是也要保证达到采样的总数。
要求:
每个模版都要采到。
废话不多说,直接上代码。
2. 相关代码
/***
* 等比例采样
* @param map 存放数据,需要按照数量正序排
* @param total 总数量
* @param sampleTotal 需要采样的数量
*/
public static void allocateFlowByPercentage(Map map, Integer total, Integer sampleTotal) {
int newTotal = 0;
int addCount = 0;
int i = 0;
double basePercentage = sampleTotal / total.doubleValue();
Iterator> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry next = iterator.next();
String key = next.getKey();
if (sampleTotal == map.size()) {
// 每个模版分1个
map.put(key, 1);
System.out.println("模版" + key + ":原来有流量:" + next.getValue() + "个,采样:1个");
newTotal+