---
title: "分组算法实现"
author: "NNBchuang"
date: "2013-04-28T16:19:47Z"
tags: ["Java", "算法"]
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2013-04-28T16:19:35Z"
id: 1856692
url: "https://nnbchuang.iteye.com/blog/1856692"
---

题目如下：
假设有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的数



```java

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);
			}
		}
	}
}


```