Program Code
import java.util.ArrayList;
import java.util.List;
public class PowerSetGenerator {
/**
* Generates the power set of a given set of integers.
*
* @param set The input set represented as an array of integers.
* @return A list of lists representing the power set.
*/
public static List<List> generatePowerSet(int[] set) {
List<List> powerSet = new ArrayList<>();
int setSize = set.length;
int powerSetSize = 1 << setSize; // 2^setSize
for (int i = 0; i < powerSetSize; i++) {
List subset = new ArrayList<>();
for (int j = 0; j < setSize; j++) {
// Check if jth element is included in the subset
if ((i & (1 << j)) > 0) {
subset.add(set[j]);
}
}
powerSet.add(subset);
}
return powerSet;
}
public static void main(String[] args) {
int[] inputSet = {1, 2, 3}; // Example input set
List<List> result = generatePowerSet(inputSet);
System.out.println("Power Set:");
for (List subset : result) {
System.out.println(subset);
}
}
}
Program Explanation
The program consists of a class named PowerSetGenerator
that contains two main methods: generatePowerSet
and main
.
Method: generatePowerSet
- Parameters: It accepts an array of integers
set
as input. - Return Value: It returns a list of lists, where each inner list represents a subset of the power set.
- Logic:
- The size of the power set is calculated as
2^n
(wheren
is the size of the input set). - A loop iterates over all possible combinations (from 0 to
powerSetSize - 1
). - For each combination, a nested loop checks which elements are included based on the bits of the integer.
- Included elements are added to a subset, which is then added to the power set.
- The size of the power set is calculated as
Method: main
- This is the entry point of the program.
- An example input set is defined, and the
generatePowerSet
method is called. - The resulting power set is printed to the console.
Usage
To use this program, you can compile and run it in any Java environment. Modify the inputSet
in the main
method to test with different sets.
Conclusion
This Java program effectively generates the power set of a given set of integers, showcasing the use of bit manipulation to explore all possible subsets.