java - How could I do this better to maximise performance and efficiency (for loop) -
i have these nested loops, there way make more efficient?
i want every combination of numbers. e.g. 2, 290, 29091993..etc combinations string arraylist.
int[] combo = new int[]{2, 9, 0, 9, 1, 9, 9, 3}; (int = 0; < combo.length; i++) { combinations.add(combo[i] + ""); (int x = 0; x < combo.length; x++) { combinations.add(combo[i] + "" + combo[x]); (int y = 0; y < combo.length; y++) { combinations.add(combo[i] + "" + combo[x] + "" + combo[y]); (int z = 0; z < combo.length; z++) { combinations.add(combo[i] + "" + combo[x] + "" + combo[y] + "" + combo[z]); (int z1 = 0; z1 < combo.length; z1++) { combinations.add(combo[i] + "" + combo[x] + "" + combo[y] + "" + combo[z] + "" + combo[z1]); (int z2 = 0; z2 < combo.length; z2++) { combinations.add(combo[i] + "" + combo[x] + "" + combo[y] + "" + combo[z] + "" + combo[z1] + "" + combo[z2]); (int z3 = 0; z3 < combo.length; z3++) { combinations.add(combo[i] + "" + combo[x] + "" + combo[y] + "" + combo[z] + "" + combo[z1] + "" + combo[z3]); } } } } } } }
void addpermutation(list<string> combinations, int level, int[] combo, stringbuilder buffer) { int length = 0; if (buffer != null) { length = buffer.length(); } else { buffer = new stringbuilder(); } if (level < combo.length) { (int x : combo) { buffer.append(integer.valueof(x)); string current = buffer.tostring(); //system.out.println(current); xxx debug purpose combinations.add(current); addpermutation(combinations,level+1,combo,buffer); buffer.setlength(length); } } } @test public void testpermutation(){ list<string> combinations = new linkedlist<string>(); int[] combo = new int[]{2, 9, 0}; addpermutation(combinations, 0, combo, null); }
of corse since it's time complexity it's lot high, can't miracles.
Comments
Post a Comment