java - all possible combination of n sets -
i have n sets. each set has different number of elements. write algorithm give me possible combinations sets. example: lets have:
s1={1,2}, s2={a,b,c}, s3={$,%,£,!}
a combination should like
c1={1,a,$} c2={1,a,%}
.... , on number of possible combination 2*3*4 = 24
please me write algorithm in java.
many in advance
recursion friend:
public class printsetcomb{ public static void main(string[] args){ string[] set1 = {"1","2"}; string[] set2 = {"a","b","c"}; string[] set3 = {"$", "%", "£", "!"}; string[][] sets = {set1, set2, set3}; printcombinations(sets, 0, ""); } private static void printcombinations(string[][] sets, int n, string prefix){ if(n >= sets.length){ system.out.println("{"+prefix.substring(0,prefix.length()-1)+"}"); return; } for(string s : sets[n]){ printcombinations(sets, n+1, prefix+s+","); } } }
in response question op generalizing sets of objects:
import java.util.arrays; public class printsetcomb{ public static void main(string[] args){ integer[] set1 = {1,2}; float[] set2 = {2.0f,1.3f,2.8f}; string[] set3 = {"$", "%", "£", "!"}; object[][] sets = {set1, set2, set3}; printcombinations(sets, 0, new object[0]); } private static void printcombinations(object[][] sets, int n, object[] prefix){ if(n >= sets.length){ string outp = "{"; for(object o: prefix){ outp = outp+o.tostring()+","; } system.out.println(outp.substring(0,outp.length()-1)+"}"); return; } for(object o : sets[n]){ object[] newprefix = arrays.copyofrange(prefix,0,prefix.length+1); newprefix[newprefix.length-1] = o; printcombinations(sets, n+1, newprefix); } } }
and iterative variant. based on increasing array of counters counter wraps , carries when reaches size of set:
import java.util.arrays; public class printsetcombiterative{ public static void main(string[] args){ string[] set1 = {"1","2"}; string[] set2 = {"a","b","c"}; string[] set3 = {"$", "%", "£", "!"}; object[][] sets = {set1, set2, set3}; printcombinations(sets); } private static void printcombinations(object[][] sets){ int[] counters = new int[sets.length]; do{ system.out.println(getcombinationstring(counters, sets)); }while(increment(counters, sets)); } private static boolean increment(int[] counters, object[][] sets){ for(int i=counters.length-1;i>=0;i--){ if(counters[i] < sets[i].length-1){ counters[i]++; return true; } else { counters[i] = 0; } } return false; } private static string getcombinationstring(int[] counters, object[][] sets){ string combo = "{"; for(int = 0; i<counters.length;i++){ combo = combo+sets[i][counters[i]]+","; } return combo.substring(0,combo.length()-1)+"}"; } }
Comments
Post a Comment