Skip to content

Commit

Permalink
#20.Generating a PowerSet using java
Browse files Browse the repository at this point in the history
  • Loading branch information
achaJackson committed Oct 2, 2017
1 parent 5116155 commit 3bf99d3
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions maths/powerset/PowerSet.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import java.util.*;
public class PowerSet {

public static <T> Set<Set<T>> powerSet( Set<T> set ) {
T[] element = (T[]) set.toArray();
final int SET_LENGTH = 1 << element.length;
Set<Set<T>> powerSet = new HashSet<>();
for( int binarySet = 0; binarySet < SET_LENGTH; binarySet++ ) {
Set<T> 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<Character> test = new HashSet<>();
test.add( 'a' );
test.add( 'b' );
test.add( 'c' );
System.out.println("test = " + test);
Set<Set<Character>> result = powerSet( test );
System.out.println( result );
}
}

0 comments on commit 3bf99d3

Please sign in to comment.