Skip to content

Instantly share code, notes, and snippets.

@hantuzun
Created September 29, 2014 08:13
Show Gist options
  • Save hantuzun/bc24dea0878dcfe5cdcb to your computer and use it in GitHub Desktop.
Save hantuzun/bc24dea0878dcfe5cdcb to your computer and use it in GitHub Desktop.
Creates all subsets of a given int array using gray codes and Integer class methods.
import java.util.Arrays;
public class subsetGenerator{
public static void main(String []args){
int[] input = {0, 1, 2, 3, 4};
int[][] subsets = subsetGenerator(input);
for (int[] subset : subsets) {
System.out.println(Arrays.toString(subset));
}
}
static int[][] subsetGenerator(int[] input) {
int size = (int) Math.pow(2, input.length);
int[][] subsets = new int[size][];
for (int i = 0; i < size; i++) {
String graycode = Integer.toBinaryString(i);
int len = graycode.length();
int bitCount = Integer.bitCount(i);
subsets[i] = new int[bitCount];
for (int j = 0, p = 0; j < len; j++) {
if (graycode.charAt((len - 1) - j) == '1') {
subsets[i][p++] = input[j];
}
}
}
return subsets;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment