分组算法实现

题目如下:
假设有n个item,k个box。将item放入box中,编写程序打印出所有可能的结果,结果包括可能出现的错误情况。

例:
假设k=3,设为a、b、c。n=10。

打印出的结果可能为:
0,0,10
0,1,9
0,2,8
1,1,8

分析为:
a+b+c = 10
a、b、c都是 大于0小于10的数



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

public class TestGroup {

public static void main(String[] args) {

// 盒子个数
int k = 3;
// 条目个数
int n = 10;

// 用于存储初始化数据
List<int[]> boxList = new ArrayList<int[]>();
// 存储过滤后的数据
List<int[]> copyBoxList = new ArrayList<int[]>();

// 初始化list
initList(boxList, k, n);

for(int[] eachbox : boxList) {
// 判断数组求和
if(!isEqualsTotal(eachbox, n)){
continue;
}
// 判断数组中是否存在前面大于后面的数据
if(isExistBeforeBig(eachbox)){
continue;
}
copyBoxList.add(eachbox);
}

for(int[] eachbox : copyBoxList) {
String boxStr = "";
for(int item : eachbox) {
boxStr = boxStr + item +",";
}
System.out.println(boxStr.substring(0, boxStr.length()-1));
}
System.out.println(copyBoxList.size());

}

// 判断数组中是否存在前面大于后面的数据
public static boolean isExistBeforeBig(int[] box) {
for(int i=0;i<box.length-1;i++) {
if(box[i] > box[i+1]) {
return true;
}
}
return false;
}

// 计算数组中的数据总和是否等于条目个数
public static boolean isEqualsTotal(int[] box, int n) {
int total = 0;
for(int i=0;i<box.length;i++) {
total += box[i];
}
return total==n;
}

// 初始化List
public static void initList(List<int[]> boxList, int k, int n) {
int[] boxArray = new int[k];
set(boxList, boxArray, n, 0, k);
}

// 递归式填充数组
public static void set(List<int[]> boxList, int[] boxArray, int n, int index, int k) {
int i = -1;
while(i++<n) {
if(index+1<k) {
boxArray[index] = i;
set(boxList, boxArray, n, index+1, k);
}else{
int[] tempBox = new int[k];
for(int m=0;m<boxArray.length;m++){
tempBox[m] = boxArray[m];
}
tempBox[k-1] = i;
boxList.add(tempBox);
}
}
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值