有n个已经编号的面,现在要把这些面按指定的面积值t进行分组,每一组面的面积总和不能超过指定值t,但是当这个面的值大于或等于d时就要单独分为一组。(注,程序是通过编号来读取面积的,可以把面积和编号放在多维数组中)示例:
t=200
d=160
编号 面积
1 30
2 110
3 80
4 90
5 20
6 73
7 180
8 80
9 40
10 50
11 170
12 80按题目要求的结果为:编号 面积
第一组
1 30
3 80
4 90
第二组
2 110
5 20
6 63
第三组
7 180
第l四组8 80
9 40
10 50第五组
11 170
第六组(由于80没有组合的对象了,就单独分为一组)
12 80
t=200
d=160
编号 面积
1 30
2 110
3 80
4 90
5 20
6 73
7 180
8 80
9 40
10 50
11 170
12 80按题目要求的结果为:编号 面积
第一组
1 30
3 80
4 90
第二组
2 110
5 20
6 63
第三组
7 180
第l四组8 80
9 40
10 50第五组
11 170
第六组(由于80没有组合的对象了,就单独分为一组)
12 80
1 “程序是通过编号来读面积的”。好像在楼主给的demo里并未体现。本人写了个方法,可大致供楼主参考一下。
public void doFun01() {
int[] id = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
int[] square = { 30, 110, 80, 90, 20, 73, 180, 80, 40, 50, 170, 80 };
int max = 200;
int single = 160;
groupSquare(id, square, max, single);
} public void groupSquare(int[] id, int[] square, int max, int single) {
if (id.length != square.length)
return;
List all = new ArrayList();
ArrayList group = new ArrayList();
int sum = 0;
for (int i = 0; i < id.length; i++) {
int index = id[i] - 1;
int value = square[index];
Map map = new HashMap();
map.put(index + "", value + "");
if (value >= single) {
List big = new ArrayList();
big.add(map);
all.add(big);
continue;
}
if (sum + value > max) {
ArrayList enough = (ArrayList) group.clone();
all.add(enough);
group.clear();
group.add(map);
sum = value;
} else {
group.add(map);
sum = sum + value;
}
}
print(all);
} public void print(List all) {
for (int i = 0; i < all.size(); i++) {
Conica.pl("\n组别:"+(i+1));
Conica.pl("编号\t面积");
List group = (List)all.get(i);
for(int j=0; j<group.size(); j++){
HashMap map = (HashMap)group.get(j);
Iterator it = map.keySet().iterator();
while(it.hasNext()){
String key = (String)it.next();
String value = (String)map.get(key);
Conica.pl(key+"\t"+value);
}
}
}
}
public void groupSquare(int[] id, int[] square, int max, int single) {
if (id.length != square.length)
return;
List all = new ArrayList();
ArrayList group = new ArrayList();
int sum = 0;
for (int i = 0; i < id.length; i++) {
int index = id[i];
int value = square[index];
Map map = new HashMap();
map.put(index+1 + "", value + "");
if (value >= single) {
List big = new ArrayList();
big.add(map);
all.add(big);
continue;
}
if (sum + value > max) {
ArrayList enough = (ArrayList) group.clone();
all.add(enough);
group.clear();
group.add(map);
sum = value;
} else {
group.add(map);
sum = sum + value;
}
}
all.add(group);
print(all);
}