diff --git a/maths/powerset/PowerSet.java b/maths/powerset/PowerSet.java new file mode 100644 index 00000000..a141c2e7 --- /dev/null +++ b/maths/powerset/PowerSet.java @@ -0,0 +1,30 @@ +import java.util.*; +public class PowerSet { + + public static Set> powerSet( Set set ) { + T[] element = (T[]) set.toArray(); + final int SET_LENGTH = 1 << element.length; + Set> powerSet = new HashSet<>(); + for( int binarySet = 0; binarySet < SET_LENGTH; binarySet++ ) { + Set subset = new HashSet<>(); + for( int bit = 0; bit < element.length; bit++ ) { + int mask = 1 << bit; + if( (binarySet & mask) != 0 ) { + subset.add( element[bit] ); + } + } + powerSet.add( subset ); + } + return powerSet; + } + + public static void main(String[] args) { + Set test = new HashSet<>(); + test.add( 'a' ); + test.add( 'b' ); + test.add( 'c' ); + System.out.println("test = " + test); + Set> result = powerSet( test ); + System.out.println( result ); + } + } \ No newline at end of file