Note that there are some explanatory texts on larger screens.

plurals
  1. POFinding Power set of a Set
    text
    copied!<p>[Homework Assignment]</p> <p>We have to find the power set of a given set using Java or C++. The set will be accepted in the form of an array of any size and I need to display the elements of the power set of that set. Note that the only concepts to use are arrays, loops and functions (recursive and iterative).</p> <p>I need someone to point me in the right direction regarding the logic I can apply. Please help.</p> <p>PS : Power set of a set A is the set of all subsets of set A Eg. A = { a, b, c} Power Set of A = {{},{a},{b},{c},{a,b},{b,c},{a,c},{a,b,c}}</p> <hr> <p>Edit:</p> <p><strong>Thanks a lot to "wy" and "MrSmith42"!</strong> I have written my program using the logic they have given. Now I am trying to optimize it. Note that I am new to Java and find it slightly uncomfortable due to its newness.</p> <p>Here's my code :</p> <pre><code>import java.util.Scanner; public class PowerSet { //Function to increment binary string... static String incr_bin (String binary){ char bin[] = new char[100]; int size_bin, i; size_bin = binary.length(); bin = binary.toCharArray(); bin[size_bin-1]++; for(i=size_bin-1; i&gt;=0; i--){ if (i != 0){ if(bin[i] &gt; '1'){ bin[i]='0'; bin[i-1]++; } } } if (bin[0]&gt;'1'){ for(i=0;i&lt;size_bin;i++){ bin[i]='0'; } } binary = new String (bin); return binary; } public static void main(String[] args) { //Declarations Scanner in = new Scanner (System.in); int a[] = new int [100]; int size_a, i, count=0; String binary; //Input System.out.println("Enter the number of elements in A : "); size_a = in.nextInt(); char bin[] = new char [size_a]; System.out.println("Enter the elements in A : "); for(i=0; i&lt;size_a; i++){ a[i] = in.nextInt(); bin[i] = '0'; } binary = new String(bin); //Calculating and Setting up subsets System.out.println("MEMBERS OF POWER SET :"); do{ System.out.print("\n{."); count = 0; binary = incr_bin(binary); bin = binary.toCharArray(); for(i=0; i&lt;size_a; i++){ if (bin[i] == '0') count++; if (bin[i] == '1') System.out.print(a[i] + " "); } System.out.println("}"); }while(count!=size_a); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload