分组算法
需求:根据每组多少人来进行分组,人数少于每组人数时,只分一组;
分组时,最后一个组的人数<=每组人数的一半时,取消该组,将该组人数分配到其他组。
lg:26人的集合,每组4人,分6组,余2个人,这个2个人分到其他组里去;
27人的集合,每组4人,分7组,最后1组3人
代码实现如下:
public class test {
public static List<List<String>> test(List<String> list, Integer n) {//n代表每组多少人
// 求余数
int yushu = list.size() % n;
// 求分组数
int count0 = list.size() / n;
boolean flag = false;
if(yushu<=n/2){
flag=true;
}
List<List<String>> data = new ArrayList<List<String>>();
// 获取多余list
List<String> sub = new ArrayList<String>(list.subList(list.size() - yushu , list.size()));
// 遍历list到余数前
for (int i = 0; i < count0+1; i++) {
List<String> ls = null;
if(flag){
if(i==count0){
break;
}
ls = new ArrayList<String>(list.subList(i * n, i * n + n));
// 将余出的数据加入分组
if (i < sub.size()) {
ls.add(sub.get(i));
}
}else{
int endex = i * n + n;
if(endex>=list.size()){
endex=list.size();
}
ls = new ArrayList<String>(list.subList(i * n, endex));
}
data.add(ls);
}
return data;
}
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
for (int i = 0; i < 5; i++) {
list.add(i + "");
}
List<List<String>> test = test(list, 5);
System.out.println("result:" + test);
}
}