Java 组合

场景:

?

String[][]arr1=new String[3][];
		arr1[0]=new String[]{"a","[^a]"};
		arr1[1]=new String[]{"b","[^b]"};
		arr1[2]=new String[]{"c","[^c]"};

?把arr1[0],arr1[1],arr1[2] 进行组合,组合的规则:

?

(1){"a","[^a]"} X?{"b","[^b]"}?X{"c","[^c]"}

(2)组合的结果中必须同时有arr1[0],arr1[1],arr1[2]中的一个元素.

比如"abc"就是正确的,a[^b]b就是错误的,因为a[^b]b没有{"c","[^c]"}中的元素.

"acb"是错误的,因为没有按顺序

/***
	 * 
	 * @param a
	 * @param aa
	 * @param index : 初始值为0
	 */
	public static List<StringBuffer> cc(String[][] aa,int index,List<StringBuffer> list){
		
		if(index>=aa.length){//说明已经遍历完成
			return list;//并不是每次循环都会执行,最后才会执行此语句.
		}
		String cc[]=aa[index];
		int length=cc.length;
		List<StringBuffer> listNew=new ArrayList<StringBuffer>();
		if(list==null||list.size()==0){//首次循环
			for(int i=0;i<length;i++){
				listNew.add(new StringBuffer(cc[i]));
			}
		}else{
			for(int i=0;i<length;i++){
				for(int j=0;j<list.size();j++){
					StringBuffer sb=list.get(j);
					StringBuffer sb2=new StringBuffer(sb);
					sb2.append(cc[i]);
					listNew.add(sb2);
				}
			}
		}
		List<StringBuffer> list33=cc(aa, ++index, listNew);
		if(!ValueWidget.isNullOrEmpty(list33)){
			return list33;
		}
		return null;
	}
	/***
	 * 组合
	 * @param aa
	 * @return
	 */
	public static List<StringBuffer>assemble(String[][] aa){
		return cc(aa, 0, null);
	}

?

?测试1:

@Test
	public void tset_cc(){
		String[][]arr1=new String[3][];
		arr1[0]=new String[]{"a","[^a]"};
		arr1[1]=new String[]{"b","[^b]"};
		arr1[2]=new String[]{"c","[^c]"};
		
		List<StringBuffer> list=assemble(arr1);
		System.out.println(list.size());
		System.out.println(list);
	}

?测试结果:

8
[abc, [^a]bc, a[^b]c, [^a][^b]c, ab[^c], [^a]b[^c], a[^b][^c], [^a][^b][^c]]

?

测试2:

@Test
	public void tset_cc2(){
		String[][]arr1=new String[3][];
		arr1[0]=new String[]{"a"};
		arr1[1]=new String[]{"b"};
		arr1[2]=new String[]{"c"};
		
		List<StringBuffer> list=assemble(arr1);
		System.out.println(list.size());
		System.out.println(list);
	}

?测试结果:

1
[abc]

?

测试3:

@Test
	public void tset_cc2(){
		String[][]arr1=new String[2][];
		arr1[0]=new String[]{"a","1","one"};
		arr1[1]=new String[]{"b","2","two"};
//		arr1[2]=new String[]{"c","3"};
		
		List<StringBuffer> list=assemble(arr1);
		System.out.println(list.size());
		System.out.println(list);
	}

?测试结果:

9
[ab, 1b, oneb, a2, 12, one2, atwo, 1two, onetwo]

?

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。