Tuesday, December 27, 2011

Find all the subsets of a given set

public class Subset {


public static List subset( List input ) {
double r = input.size();
int finalsize = (int)Math.pow( 2d, r );
List ret = new ArrayList( finalsize );
int one = 0x0001;
for ( int i = 1; i < finalsize; i++ ) {
int count = 0;
StringBuilder sb = new StringBuilder();
while ( count < finalsize ) {
int k = (i >> count) & one;
if ( k == 1 ) {
sb.append( input.get( count ) ).append(",");
}
count++;

}
ret.add( sb.toString() );
}
return ret;
}

public static void print( List in ) {
int i =1;
for ( String s : in ) {
System.out.println( "count_" + (i++) + " :" + s );
}
}

public static void main( String[] args ) {
List in = new ArrayList();
in.add( "a" );
in.add( "b" );
in.add( "c" );
in.add( "d" );
print ( subset( in) );
}
}

No comments:

Post a Comment