Skip to content

Commit

Permalink
Merge pull request #77 from achaJackson/master
Browse files Browse the repository at this point in the history
#20. Generating and Implementing a Power set with Java
  • Loading branch information
srbcheema1 authored Oct 3, 2017
2 parents c5c7f6f + 3bf99d3 commit b2565ad
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 b2565ad

Please sign in to comment.