Tuesday, December 13, 2011

Java program to find subsets

This is the java program to find subsets. This is  simple and small code. Subsets program can be used in many logical applications.Consider the following subsets program in java.

/* java program to find subsets */
import java.io.*;
public class subset
{   
public static void main(String[] args) throws IOException
int tot_elements = 0;
int count = 0;
System.out.println("Enter Total No Of Elements:");
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
tot_elements = Integer.parseInt(bf.readLine());       
final int loopBound = (1 << tot_elements) - 1; 
for (int i = 0; i <= loopBound; i++)
{
printSubset(i, tot_elements);
count++;
}
System.out.println("Total No Of Elements:"+count);
}  
private static void printSubset(int ordinal, int tot_elements)
{  
if (ordinal == 0) // throw away empty set           
return;  
boolean firstElem = true;     
System.out.print('{');  
int mask = 1;  
final int loopBound = (1 << tot_elements) - 1;
for (int i = 0; i <= loopBound; i++)
{  
if ((ordinal & mask) > 0)
{              
if (!firstElem)
System.out.print(", ");               
}
else
{  
firstElem = false;               
System.out.print((int) (1 + i)); 
}  
mask <<= 1;
}      
System.out.println('}');   
}
}

Output: