Skip to content

Instantly share code, notes, and snippets.

@janakagamini
Created August 31, 2016 02:52
Show Gist options
  • Save janakagamini/ccd22c6ef17c6db185bf2fb32b42c810 to your computer and use it in GitHub Desktop.
Save janakagamini/ccd22c6ef17c6db185bf2fb32b42c810 to your computer and use it in GitHub Desktop.
A power set generator that can filter out sets that don't include a particular element.
import java.util.LinkedHashSet;
public class PowerSetUtil {
/**
* Returns the power set from the given set by using a binary counter
* Example: S = {a,b,c}
* P(S) = {[], [c], [b], [b, c], [a], [a, c], [a, b], [a, b, c]}
* @param set String[]
* @return LinkedHashSet
*/
public static LinkedHashSet powerset(String[] set) {
//create the empty power set
LinkedHashSet power = new LinkedHashSet();
//get the number of elements in the set
int elements = set.length;
//the number of members of a power set is 2^n
int powerElements = (int) Math.pow(2,elements);
//run a binary counter for the number of power elements
for (int i = 0; i < powerElements; i++) {
//convert the binary number to a string containing n digits
String binary = intToBinary(i, elements);
//create a new set
LinkedHashSet innerSet = new LinkedHashSet();
//convert each digit in the current binary number to the corresponding element
//in the given set
if (binary.charAt(0) == '1') { // Filters out power sets that don't include the first element.
for (int j = 0; j < binary.length(); j++) {
if (binary.charAt(j) == '1')
innerSet.add(set[j]);
}
//add the new set to the power set
power.add(innerSet);
}
}
return power;
}
/**
* Converts the given integer to a String representing a binary number
* with the specified number of digits
* For example when using 4 digits the binary 1 is 0001
* @param binary int
* @param digits int
* @return String
*/
private static String intToBinary(int binary, int digits) {
String temp = Integer.toBinaryString(binary);
int foundDigits = temp.length();
String returner = temp;
for (int i = foundDigits; i < digits; i++) {
returner = "0" + returner;
}
return returner;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment