I solved the problem to print all possible subsets of an array. I just want to know a better approach or anything different I could have done.
Question: Print all possible subsets of an array.
My approach: I know that there are \$2^N\$ (no. of elements in the set) subsets and each subset can be represented with the help of \$N\$-bit binary number. As a part of an assignment I have already made a decimal to binary and to reverse(prints no. in reverse digit by digit) a number program.So I combined the two to solve this question.
Input: {1, 2, 3}
Output: 3, 2, 32, 1, 31, 21, 321
My Code:
private static void subset(int[] arr) {
int size = arr.length;
int binaryLimit = (int) Math.pow(2, size) - 1;
for (int i = 0; i <= binaryLimit; i++) { //generate decimal no.
//generate corresponding binary no & counter(how many bit binary no. is)
int N = i;
int counter = 0;
int power = 0, binary = 0;
while (N != 0) {
int rem = N % 2;
rem = rem * ((int) Math.pow(10, power));
binary = binary + rem;
N = N / 2;
power++;
counter++;
}
// loop to traverse array
for (int j = arr.length - 1; j >= arr.length - counter; j--) {
// if binary no is greater then one digit, compare each digit separately.
if (counter > 1) {
int k = binary;
while (k != 0) {
int rem = k % 10;
if (rem == 1) { //if binary digit == 1, print corresponding no. from array
System.out.print(arr[j]);
}
j--;
k = k / 10;
}
System.out.println();
} else {
if (binary == 1) {
System.out.println(arr[j]);
j--;
}
}
}
}
}