To solve the described task, you can use the following Go program. This program reads the contents of input.txt, where each line represents the items in a rucksack. It then processes each line to find the item type that appears in both compartments and calculates the sum of the priorities of these item types.
package main
import (
"bufio"
"fmt"
"os"
)
func itemPriority(item rune) int {
if item >= 'a' && item <= 'z' {
return int(item - 'a' + 1)
}
return int(item-'A') + 27
}
func main() {
file, err := os.Open("input.txt")
if err != nil {
fmt.Println("Error opening file:", err)
return
}
defer file.Close()
var sum int
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
half := len(line) / 2
firstCompartment := line[:half]
secondCompartment := line[half:]
compartmentMap := make(map[rune]int)
for _, item := range firstCompartment {
compartmentMap[item]++
}
for _, item := range secondCompartment {
if _, exists := compartmentMap[item]; exists {
sum += itemPriority(item)
break
}
}
}
if err := scanner.Err(); err != nil {
fmt.Println("Error reading file:", err)
return
}
fmt.Println("Sum of item type priorities:", sum)
}
This program defines a helper function itemPriority to calculate the priority of each item type based on its character code. It then reads the input.txt file line by line, splits each line into two compartments, and uses a map to find the item type that appears in both compartments. It sums up the priorities of these item types and prints the result.
To run the program, ensure you have Go installed on your system, save the program in a file (e.g., main.go), place the input.txt file with the rucksack items in the same directory, and then execute the program by running go run main.go from a terminal or command prompt in the directory containing your main.go and input.txt.