aoc/2022/day-01/main.go
2023-11-20 19:32:28 +01:00

61 lines
1.0 KiB
Go

package main
import (
"embed"
"fmt"
"io/fs"
"os"
"sort"
"strconv"
"strings"
)
//go:embed input
var input embed.FS
func main() {
data, err := fs.ReadFile(input, "input")
if err != nil {
fmt.Printf("ERROR: failed to read input: %s", err)
os.Exit(1)
}
backpacks := strings.Split(string(data), "\n\n")
largestBackpack := 0
var topBackPacks = []int{0, 0, 0}
for _, backpack := range backpacks {
contents := 0
for _, item := range strings.Split(backpack, "\n") {
if item == "" { continue }
itemInt, err := strconv.Atoi(item)
if err != nil {
panic("failed to parse line")
}
contents += itemInt
}
if contents > largestBackpack {
largestBackpack = contents
}
if contents > topBackPacks[0] {
topBackPacks[0] = contents
}
sort.Ints(topBackPacks)
}
total := 0
for _, numb := range topBackPacks {
total += numb
}
fmt.Printf("The largest backpack contains %d calories\n", largestBackpack)
fmt.Printf("The top 3 largest backpacks contain %d calories\n", total)
}