Program Code
package main
import (
"fmt"
)
// unionIntersection takes two slices of integers and returns their union and intersection.
func unionIntersection(arr1, arr2 []int) ([]int, []int) {
// Use maps to track unique elements
elementMap := make(map[int]bool)
intersection := make([]int, 0)
// Add elements of the first array to the map
for _, num := range arr1 {
elementMap[num] = true
}
// Prepare to collect the union
union := make([]int, 0, len(arr1)+len(arr2))
// Process the second array
for _, num := range arr2 {
// Check for union
if _, exists := elementMap[num]; !exists {
union = append(union, num)
} else {
// If it exists in both, it's part of the intersection
intersection = append(intersection, num)
}
}
// Append the unique elements from the first array to union
for num := range elementMap {
union = append(union, num)
}
return union, intersection
}
func main() {
arr1 := []int{1, 2, 3, 4, 5}
arr2 := []int{4, 5, 6, 7, 8}
union, intersection := unionIntersection(arr1, arr2)
fmt.Println("Union:", union)
fmt.Println("Intersection:", intersection)
}
Explanation of the Program Structure
The program consists of a main function and a helper function called unionIntersection
.
1. Imports
The program imports the fmt
package, which is used for formatted I/O operations.
2. unionIntersection Function
This function takes two slices of integers as input and returns two slices: one for the union and one for the intersection.
elementMap
: A map is created to store unique elements from the first array.intersection
: A slice to hold elements that exist in both arrays.- The first loop populates
elementMap
with elements fromarr1
. - The second loop processes
arr2
. If an element is not inelementMap
, it’s added to the union; if it exists, it’s added to the intersection. - Finally, elements from
elementMap
are appended to the union slice.
3. Main Function
The main
function initializes two arrays and calls the unionIntersection
function. The results are then printed to the console.
Conclusion
This program efficiently calculates the union and intersection of two integer arrays using hashing, ensuring unique values are processed effectively.