arraylist - How to implement recursive all possible combination of any set (JAVA) -
can give me few clues or writing combination function output possible combination of set. have idea. find hard.
something in java.
string set[] = {"java","c++","python"}; arraylist<string> list = new arraylist<string>(); public void combination(string[] set) { if (set.length == 0) { nothing } else if (this combination set) { add list } }
here's simple example of combinations of letters in string, give algorithm. see if can transfer algorithm example.
public class stringlib { public static void combine(string str){ int length=str.length(); stringbuffer output=new stringbuffer(); combination(str,length,output,0); } static void combination(string str, int length, stringbuffer output, int level){ /* show arms-length recursion style better peformance */ if (level==length) return; else{ for(int i=level;i<length;i++){ output.append(str.charat(i)); system.out.println(output.tostring()); combination(str,length,output,i+1); output.deletecharat(output.length()-1); } } } public static void main(string[] args){ combine("abc"); } } /*output: ab abc ac b bc c */
just in case need permutations:
import java.util.*; public class permutations { public static void main(string[] args) { string str = new string("abc"); stringbuffer output = new stringbuffer(); boolean used[] = {false, false, false}; permute.printpermutations(0, output, used, str); } } public class permute{ static void printpermutations(int level, stringbuffer output, boolean used[], string orig){ int len = orig.length(); if (level == len){ system.out.println(output); } else{ (int = 0; < len; i++){ //recurse if not used if (!used[i]){ output.append(orig.charat(i)); used[i] = true; printpermutations(level+1, output, used, orig); output.deletecharat(output.length() - 1); used[i] = false; } } } } } /*output: abc acb bac bca cab cba */
Comments
Post a Comment