Question

The Power Set of a set of (distinct) objects S is the set of all subsets...

The Power Set of a set of (distinct) objects S is the set of all subsets of S, including S itself and an empty set. For example, let S be a set of words: S={Hello, World, Students}. Then possible subsets are: {Hello} {World} {Students} {Hello, World} {Hello, Students} {World, Students} {Hello, World, Students} From a course in Discrete Mathematics, you should know that if S contains n elements, then its power set consists of 2^n elements. Please write a recursive algorithm, which will take an array of objects as an input and return an array of arrays of objects as the power set. In the previous example, our objects were strings, and the output was an array of arrays of strings. Right? In order to do that, please develop the following method: public static Object[][] GeneratePowerSet(Object[] arr) Please do not forget to check "boundary cases" and possible invalid inputs like some objects in arr are null. If that happens, your function should print an error message and return null. (Note that in real world programming, I would suggest to throw an exception instead of printing an error message; we will talk about this later in our course.) Please also test the method by feeding it an array of integers and printing out the power set. You can do this for testing: Integer[] my_arr = {-2,7,10,23,19}; Integer[][] pSet = GeneratePowerSet(my_arr); for(int i=0; i System.out.print("{"); for(int j=0; j System.out.print(pSet[i][j]); if(j+1 System.out.print(", "); } System.out.println("}"); } Side Note: Please note that if you want to print out an object (whatever it means) by calling System.out.println(my_object); the toString() method of that object would be called inside println(). It is the same as the following call: System.out.println(my_object.toString()); I encourage you to exercise with toString() method for a simple class ComplexNumber you can easily create: class ComplexNumber { public double Re; public double Im; public ComplexNumber(double x, double y) { super(); this.Re = x; this.Im = y; } public String toString() { // your code inside returning something like (Re,Im) } }

Homework Answers

Answer #1

The code is given below along with screenshot. Explanation is given in comments alongside code. Let me know in the comments if you have any doubts.

Code:

import java.util.*;
public class Main
{   
public static Object[][] powerSet(Object[] arr) //Generating power set for array
{   
long p_size=(long)Math.pow(2, arr.length);
Object result[][]=new Object[(int)p_size][]; //Array to store our result and return it
/*
The idea behind this approach is we will first find the number of sets in the power set
which is equal to 2^n where n is the number of elements in the set. Now the approach is as follows
Suppose we want to find the power set for the set {1,2,3}. The number of elements in the powerset
would be 2^3=8. We would run a loop from 0 to 7 i.e. <8. And we would check which bits are set for i
and the bit that is set, we would add that element to our set that would be included in the powerset.
For example, if i=6, then in binary, it would 110, so the elements that would be included in the current set
would be 1 and 2. So, {1,2} would be included in the power set. Similarly for all values of i
  
*/
for(int i=0;i<p_size;i++) //Running loop from 0 to less than size of power set
{ ArrayList<Object> temp=new ArrayList<Object>(); //Creating a temp arrayList to store elements
//that would be included in the current set
  
  
/*
This is the best way to check what bits are set in a number. We would run the inner loop for all the
elements present in our original array and for each index j, we would check if jth bit is set or not is by left shifting
1 by j bits. For example, for j=2, we would left shift bits in 1 by 2 bits which would make it 100. After that,
we would bitwise AND this with our current value of power set counter to see if jth bit is set or not. If the result is
1, it is set, otherwise jth bit is not set.
For example, suppose i is 8 in the current iteration. And value of j is 2.
8 in binary=1000
1<<2 in binary= 4 in binary=0100
1000 & 0100 ==0
So, 2nd element would not be included in the current set as jth bit is not set.
  
*/
  
for(int j=0;j<arr.length;j++)
{   
  
if((i & (1<<j))>0)
temp.add(arr[j]); //If jth bit is set, put in arrayList
  
}
result[i]=temp.toArray(); //Converting arrayList into array and storing it in our result array
}
  
return result; //Returning the result
}
   public static void main(String[] args) {
       Integer myarr[]= {-2,7,10,23,19}; //Creating array for testing
      
       Object[][] pSet = powerSet(myarr); //Calling the function for myarr
       for(int i=0;i<pSet.length;i++) //Printing the power set
       {
       for(int j=0;j<pSet[i].length;j++)
       {
       System.out.print(pSet[i][j]+" ");
       }
       System.out.println();
       }
      
   }
}

Output:

Code for toString method excercise:

class ComplexNumber
{
public double Re;
public double Im;
public ComplexNumber (double x, double y)
{
super ();
this.Re = x;
this.Im = y;
}
  
public String toString ()
{               // your code inside returning something like (Re,Im)
  
return "("+this.Re+" "+this.Im+")"; //We just return the string that we want to print for the object
//In this case, we want to print (Re, Im) when our object is passed in println function, so we just return
// a string in that format
}
  
}
public class Main
{
public static void main (String[]args)
{
ComplexNumber a =new ComplexNumber(10,12);
   System.out.println (a);
}
}
Output:

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
Do a theta analysis and count the number of computations it performed in each function/method of...
Do a theta analysis and count the number of computations it performed in each function/method of the following code: import java.io.*; import java.util.Scanner; class sort { int a[]; int n; long endTime ; long totalTime; long startTime; static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public sort(int nn) // Constructor { a = new int[nn]; n = nn; endTime= 0; totalTime =0; startTime =0; } public static void main(String args[]) throws IOException { System.out.print("\nEnter number of students: "); int nn =...
JAVA please Arrays are a very powerful data structure with which you must become very familiar....
JAVA please Arrays are a very powerful data structure with which you must become very familiar. Arrays hold more than one object. The objects must be of the same type. If the array is an integer array then all the objects in the array must be integers. The object in the array is associated with an integer index which can be used to locate the object. The first object of the array has index 0. There are many problems where...
Write a method that returns the sum of all the elements in a specified column in...
Write a method that returns the sum of all the elements in a specified column in a 3 x 4 matrix using the following header: public static double sumColumn(double[][] m, int columnIndex) The program should be broken down into methods, menu-driven, and check for proper input, etc. The problem I'm having is I'm trying to get my menu to execute the runProgram method. I'm not sure what should be in the parentheses to direct choice "1" to the method. I'm...
Please create an array of Leg objects, one constructor that takes three parameters as constant C...
Please create an array of Leg objects, one constructor that takes three parameters as constant C string, and one number representing the distance in miles between the two cities Write a code block to create a static array (that is, not dynamic and not a vector) of 3 Leg objects using city names of your choosing. That's THREE objects, each created using THREE parameters. For example, the Leg class declaration looked like, class Leg { const char* const startCity; const...
In this assignment, you will be building upon the work that you did in Lab #5A...
In this assignment, you will be building upon the work that you did in Lab #5A by expanding the original classes that you implemented to represent circles and simple polygons. Assuming that you have completed Lab #5A (and do not move on to this assignment unless you have!), copy your Circle, Rectangle, and Triangle classes from that assignment into a new NetBeans project, then make the following changes: Create a new Point class containing X and Y coordinates as its...
Sort by the following (name, address, dependent and gender) of these and ask the user which...
Sort by the following (name, address, dependent and gender) of these and ask the user which field to sort by !. this mean the following java must sort by address if we need, by name , by dependent , and by gender it depend on the following java it must have an option which we need to sort. please i need your help now, you just add the sorting on the following java. // Use a custom comparator. import java.io.BufferedReader;...
8.15 *zyLab: Method Library (Required & Human Graded) This code works but there are some problems...
8.15 *zyLab: Method Library (Required & Human Graded) This code works but there are some problems that need to be corrected. Your task is to complete it to course style and documentation standards CS 200 Style Guide. This project will be human graded. This class contains a set of methods. The main method contains some examples of using the methods. Figure out what each method does and style and document it appropriately. The display method is done for you and...
[Java] I'm not sure how to implement the code. Please check my code at the bottom....
[Java] I'm not sure how to implement the code. Please check my code at the bottom. In this problem you will write several static methods to work with arrays and ArrayLists. Remember that a static method does not work on the instance variables of the class. All the data needed is provided in the parameters. Call the class Util. Notice how the methods are invoked in UtilTester. public static int min(int[] array) gets the minimum value in the array public...
Please explain code 1 and code 2 for each lines code 1 public class MyQueue {...
Please explain code 1 and code 2 for each lines code 1 public class MyQueue {    public static final int DEFAULT_SIZE = 10;    private Object data[];    private int index; code 2 package test; import java.util.*; /* Class Node */ class Node { protected Object data; protected Node link; /* Constructor */ public Node() { link = null; data = 0; } /* Constructor */ public Node(Object d,Node n) { data = d; link = n; } /*...
create an array of Vehicle references. Within the application, you assign Sailboat objects and Bicycle objects...
create an array of Vehicle references. Within the application, you assign Sailboat objects and Bicycle objects to the same array. Then, because the different object types are stored in the same array, you can easily manipulate them by using a for loop. 1. Open a new file, and then enter the following first few lines of the VehicleDatabase program: import javax.swing.*; public class VehicleDatabase { public static void main(String[] args) { 2. Create the following array of five Vehicle references...