In: Computer Science
Can you write code in Java to find the power set of a given set? For example if S={a,b} the power set is P={{},{a},{b},{a,b}} ( you can also choose any of your favorite programming language). Explaning the code in comment please.
import java.util.*;
public class Main
{
static LinkedList <String> list ;
public static void powerSet(String set[],int setSize)
{
list = new LinkedList<String>();
/*calculating the length of power set,
if set length is n then power set length = 2^n */
int powerSetSize = (int)Math.pow(2,setSize);
int counter,i;
//run counter from 000 to 111
for(counter = 0; counter < powerSetSize; counter++)
{ String powerSetElement ="";
for(i = 0; i < setSize; i++)
{
/*check if ith bit in the counter is set,
then add element from set to powerSetElement
*/
if((counter & (1 << i)) > 0)
{
powerSetElement = powerSetElement+set[i];
}
}
// add powerSetElement element into list,
list.add(powerSetElement);
}
}
   public static void main(String[] args)
   {
   //set element
       String set[] = {"a","b","c"};
       // powerSet method that
generate a power set element into list,
       powerSet(set,3);
       /*printin all power set
element into power set formate,
       ex - :
{{},{a},{b},{ab}}*/
       System.out.print("{");
       for(int i = 0; i <
list.size()-1; i++ )
       {
      
System.out.print("{"+list.get(i)+"},");
       }
      
System.out.print("{"+list.get(list.size()-1)+"}"+"}");
   }
}


