Reputation: 19612
I have a char array of A, B, C and I want to print the output as:
A,B,C,AB,AC,BC,ABC
Any suggestions will be appreciated...
public class CharArray {
public static void main(String[] args) {
char alpha[] = {'A', 'B', 'C'};
for(char s : alpha) {
//what to do now
}
}
}
Upvotes: 3
Views: 1817
Reputation: 36
Another option to consider is in guava (an open source java library by google).
Sets (a set utilities class)
/** Returns the set of all possible subsets of set. For example, powerSet(ImmutableSet.of(1, 2)) returns the set {{}, {1}, {2}, {1, 2}}... */
public static <E> Set<Set<E>> powerSet(Set<E> set)
Upvotes: 0
Reputation: 726599
This prints combinations, as in your example, not permutations, as in the title of the question.
char alpha[] = {'A', 'B', 'C'};
for (int m = 1 ; m != 1<<alpha.length ; m++) {
for (int i = 0 ; i != alpha.length ; i++) {
if ((m & (1<<i)) != 0) {
System.out.print(alpha[i]);
}
}
System.out.println();
}
Upvotes: 6