Monday, 10 February 2014

Find all the subsets of a given String(up to 32 length)

Note: Input string must have no repeated character and whitespace.
Code :

import java.util.Scanner;

public class Subset {

public static void main(String args[])
{
String s;

System.out.println("Enter String:");
Scanner in= new Scanner(System.in);
s=in.nextLine();
    int l=s.length();
System.out.println("Subset are:");
int p=(int) (Math.pow(2, l)-1);

for(int i=0;i<=p;i++)

String sub=String.format("%"+l+"s", Integer.toBinaryString(i)).replace(' ', '0');

int j=0;
System.out.print("{");
while(j<l)
{
char s2=sub.charAt(j);
if(s2=='1')
{
System.out.print(s.charAt(j));

}
j++;
}
System.out.print("}");
System.out.println();
}

}

}

Output:

Enter String:
abcd
Subset are:
{}
{d}
{c}
{cd}
{b}
{bd}
{bc}
{bcd}
{a}
{ad}
{ac}
{acd}
{ab}
{abd}
{abc}
{abcd}