This program generates the power set of a given set of integers. The power set is the set of all subsets, including the empty set and the set itself. The size of the power set for a set with n
elements is 2^n
.
Go Program
package main
import (
"fmt"
)
// powerSet function generates the power set of the given set.
func powerSet(set []int) [][]int {
// Calculate the size of the power set (2^n)
n := len(set)
powerSetSize := 1 << n // This is equivalent to 2^n
result := make([][]int, 0, powerSetSize) // Create a slice of slices for storing subsets
// Iterate through all numbers from 0 to 2^n - 1, which represents the binary representation of subsets
for i := 0; i < powerSetSize; i++ {
subset := []int{} // Create a temporary slice for the current subset
// Iterate over each element in the set and determine if it is included in the current subset
for j := 0; j < n; j++ {
// Check if the j-th bit of i is set (i.e., if the element at index j is part of the subset)
if i&(1<<j) != 0 {
subset = append(subset, set[j])
}
}
// Append the subset to the result
result = append(result, subset)
}
return result
}
func main() {
// Example set
set := []int{1, 2, 3}
// Generate the power set
result := powerSet(set)
// Print the power set
fmt.Println("Power set:")
for _, subset := range result {
fmt.Println(subset)
}
}
Explanation of the Program
- powerSet function:This function takes a slice of integers as input and returns a slice of slices (representing all the subsets). It uses a loop to generate all possible combinations of the elements of the input set. Each combination corresponds to a subset, which is generated by checking each bit of the current number (from 0 to 2^n – 1). A bit is set if the corresponding element is included in the subset.
- n and powerSetSize:The number of elements in the set is stored in
n
. The size of the power set is2^n
, which is computed using bit shifting:1 << n
. This represents the number of possible subsets. - Iterating over all possible subsets:A loop from
i = 0
toi = 2^n - 1
is used. The binary representation of eachi
corresponds to whether each element in the set is included in the current subset. If thej-th
bit ofi
is 1, thej-th
element is included in the subset. - Appending the subset:A temporary slice
subset
is created for each subset. After determining which elements are included, the subset is added to the result slice. - Output:After generating all subsets, the program prints the power set to the console.
Sample Output
Power set: [] [1] [2] [1 2] [3] [1 3] [2 3] [1 2 3]
Conclusion
This Go program successfully generates and prints the power set of a given set. It uses bitwise operations to efficiently compute all possible subsets. The power set includes the empty set, all single-element subsets, and all combinations of elements from the input set.