Created
September 29, 2014 08:13
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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