I must combine values in a set in this way:
Input:
{A,B,C,D}
Result:
{AB, ABC, AC, AD, ACD, ABD, ABCD, BC, BD, BCD, CD}
How can I do this?
I must combine values in a set in this way:
Input:
{A,B,C,D}
Result:
{AB, ABC, AC, AD, ACD, ABD, ABCD, BC, BD, BCD, CD}
How can I do this?
There are several solutions depending upon the size of the input:
If the input-array is <= 64 and the input doesn't need to be sorted, we can represent each combination as a long
, where each bit is 1, if the corresponding element is in the produced output:
void generateCombination(int[] inp){
long upper_bound = (1 << inp.length);
for(long rep = 0 ; rep < upper_bound ; rep++){
for(int i = 0 ; i < inp.length ; i++)
if(rep & (1 << i) != 0)
System.out.print(inp[i]);
System.out.print(",");
}
}
If the output has to be sorted, we can easily solve this problem using a recursive solution:
void generateCombinations(int[] inp , int[] combination , int at_i , int at_c){
for(int i = at_i + 1 ; i < inp.length ; ++i)
{
combination[at_c] = inp[i];
System.out.println(Arrays.toString(combination));
generateCombinations(inp , combination , i , at_c + 1);
}
combination[at_c] = 0;
}
//this call will produce all combinations sorted ascending
generateCombinations(inpt , new int[inp.length] , -1 , 0);