求助大神,一道java关于排列组合穷举问题。
本帖最后由 lvpiggy1 于 2013-07-28 21:19:41 编辑 问题是这样的,有12个球,分别编号为1至12。 现在要求将他们分为4组,每组3个。12号球始终放在最后一组。最困难的是需要将分好的结果遍历显示出来。 我是新人,这程序想破头还没想出来怎么写,只能上网求助了。。
显示结果模板:
组1:
1,2,3
4,5,6
7,8,9
10,11,12
组2:
1,2,4
3,5,6
7,8,9
10,11,12
.
.
.
求大神指点!最好能将程序贴出来~!~! 别光写个思路 谢谢了!!!!! Java 遍历
[解决办法]
不要求将所有的可能都排列出来吧?这里随便写个随即生成的方法参考下好了:
public static void main(String[] args) {
Random r = new Random();//随机数生成器
//存储1~11的数,12固定最后一个
List<Integer> list = new ArrayList<Integer>();
Integer temp;//辅助变量
while(list.size()<11){
temp = r.nextInt(11)+1;//随机生成的数是0到10
if(list.contains(temp))
{
continue;
}
list.add(temp);
}
//最后一个12放进去
list.add(12);
//二维数组存储
int[][] arr = new int[4][3];
int index=0;
for(int i=0;i<4;i++)
{
for(int j=0;j<3;j++)
{
arr[i][j]=list.get(index++);
}
}
//打印
for(int i=0;i<4;i++)
{
for(int j=0;j<3;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println();//一行结束,打印换行
}
}
[解决办法]
组合工具类: http://blog.csdn.net/raistlic/article/details/7844812
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class CombinationTest {
public static void main(String[] args) {
List<Integer> elevenBalls = Arrays.asList(
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
);
Set<Integer> rest = new HashSet<Integer>(11);
Set<Integer> rest1 = new HashSet<Integer>(8);
Set<Integer> rest2 = new HashSet<Integer>(5);
for(List<Integer> c : Combination.of(elevenBalls, 3)) {
rest.clear();
rest.addAll(elevenBalls);
rest.removeAll(c);
for(List<Integer> c1 : Combination.of(rest, 3)) {
rest1.clear();
rest1.addAll(rest);
rest1.removeAll(c1);
for(List<Integer> c2 : Combination.of(rest1, 3)) {
rest2.clear();
rest2.addAll(rest1);
rest2.removeAll(c2);
rest2.add(12);
System.out.println(c + "; " + c1 + "; " + c2 + "; " + rest2);
}
}
}
}
}
run:
[1, 2, 3]; [4, 5, 6]; [7, 8, 9]; [10, 11, 12]
[1, 2, 3]; [4, 5, 6]; [7, 8, 10]; [9, 11, 12]
[1, 2, 3]; [4, 5, 6]; [7, 8, 11]; [9, 10, 12]
[1, 2, 3]; [4, 5, 6]; [7, 9, 10]; [8, 11, 12]
[1, 2, 3]; [4, 5, 6]; [7, 9, 11]; [8, 10, 12]
[1, 2, 3]; [4, 5, 6]; [7, 10, 11]; [8, 9, 12]
[1, 2, 3]; [4, 5, 6]; [8, 9, 10]; [11, 12, 7]
[1, 2, 3]; [4, 5, 6]; [8, 9, 11]; [10, 12, 7]
[1, 2, 3]; [4, 5, 6]; [8, 10, 11]; [9, 12, 7]
[1, 2, 3]; [4, 5, 6]; [9, 10, 11]; [8, 12, 7]
[1, 2, 3]; [4, 5, 7]; [6, 8, 9]; [10, 11, 12]
[1, 2, 3]; [4, 5, 7]; [6, 8, 10]; [9, 11, 12]
[1, 2, 3]; [4, 5, 7]; [6, 8, 11]; [9, 10, 12]
[1, 2, 3]; [4, 5, 7]; [6, 9, 10]; [8, 11, 12]
[1, 2, 3]; [4, 5, 7]; [6, 9, 11]; [8, 10, 12]
[1, 2, 3]; [4, 5, 7]; [6, 10, 11]; [8, 9, 12]
[1, 2, 3]; [4, 5, 7]; [8, 9, 10]; [11, 12, 6]
[1, 2, 3]; [4, 5, 7]; [8, 9, 11]; [10, 12, 6]
[1, 2, 3]; [4, 5, 7]; [8, 10, 11]; [9, 12, 6]
[1, 2, 3]; [4, 5, 7]; [9, 10, 11]; [8, 12, 6]
[1, 2, 3]; [4, 5, 8]; [6, 7, 9]; [10, 11, 12]
[1, 2, 3]; [4, 5, 8]; [6, 7, 10]; [9, 11, 12]
[1, 2, 3]; [4, 5, 8]; [6, 7, 11]; [9, 10, 12]
[1, 2, 3]; [4, 5, 8]; [6, 9, 10]; [11, 12, 7]
…………(结果太长,不贴了)
BUILD SUCCESSFUL (total time: 7 seconds)