问题描述
大家好,想达到如下目的,List1 {"A1", "A2", "A3", "A4"}List2 {"B1", "B2", "B3", "B4", "B5"}List3 {"C1", "C2", "C3", "C4", "C5"}List4 {"D1", "D2", "D3"}List5 {"E1", "E2", "E3", "E4"}List6 {"F1", "F2", "F3", "F4", "F5"}A1,B1,C1,D1,E1,F1A1,B1,C1,D1,E1,F2A1,B1,C1,D1,E1,F3...A1,B1,C1,D1,E2,F1A1,B1,C1,D1,E2,F2A1,B1,C1,D1,E2,F3...实现这样的组合,除了6重循环外,有什么优雅的写法吗?
解决方案
6重循环逻辑上更简单些,不想要这种写法也是可以的,给你个参考吧;import java.util.Arrays;import java.util.List;public class Mm {/** * @param args */public static void main(String[] args) {// int[] a = new int[] { 123, 11 };List<String>[] t = new List[] { Arrays.asList("1", "2", "3", "4"),Arrays.asList("a", "b", "c"), Arrays.asList("甲", "乙", "丙", "丁") };int[] pos = new int[t.length];while (!print(t, pos)) {addpos(t, pos, pos.length - 1);}}public static void addpos(List<String>[] t, int[] pos, int p_length) {if (p_length < 0)return;if (pos[p_length] < t[p_length].size() - 1) {pos[p_length] = pos[p_length] + 1;} else {pos[p_length] = 0;addpos(t, pos, p_length - 1);}}public static boolean print(List<String>[] t, int[] pos) {boolean end = true;for (int i = 0; i < pos.length; i++) {System.out.print(t[i].get(pos[i]));end = end && t[i].size() - 1 == pos[i];}System.out.println();return end;}}
解决方案二:
来个javascript的,java的类似~var sids = [[1, 2], [2, 3], [4, 2], [7, 3], [9, 5]];var vmap = {};vmap['spec.1'] = [['a','A'],['b','B']];vmap['spec.2'] = [['e','E'],['f','F'],['k','K']];vmap['spec.4'] = [['1','1'],['2','2']];vmap['spec.7'] = [['x','x1'],['y','y2'],['z','z3']];vmap['spec.9'] = [['m','MM'],['n','NN'],['V','VV'],['O','OO'],['p','PP']];//2*3*2*3=36 var d=[];function js_fill(){ var h=1, w=sids.length; for (var i=0; i<w; i++) h*=sids[i][1]; for (var i=0; i<h; i++) d[i]=[]; var jc=1, cs=0, cf=0; for (var i=0; i<w; i++) { var x=0, n=sids[i][1], ar=vmap['spec.'+sids[i][0]]; jc*=n; cf=h/jc; cs=h/(n*cf); for (var m=0; m<cs; m++) { for (var j=0; j<n; j++) { for (var k=0; k<cf; k++) d[x++][i] = ar[j]; } } //if (x!=h) alert('[test] here x!=h [x='+x+'] [h='+h+'] >> ['+jc+' >> '+cs+' >> '+cf+' >> '+(cs*n*cf)+'] bad ~ '); } var lst = '<hr />'; for (var i=0; i<h; i++) { for (var j=0; j<w; j++) { lst += d[i][j][0]+','+d[i][j][1]+' ' } lst += '<br />'; } document.write(lst);}js_fill();
解决方案三:
这是求6个列表的笛卡尔乘积,可以找找看有没有相应语言的library。以下是Python代码:list = [a, b]for x in itertools.product(*list): print x
解决方案四:
6重循环最简单了,要优雅用一些排列组合的算法,可能会慢