Advent of Code 2022 Day 1: Calorie Counting
By Andreas Røssland
https://adventofcode.com/2022/day/01 https://github.com/roessland/advent-of-code
Today’s problem is to sum and group the numbers in a list, and return the top three groups, sorted by their sum. Just a simple warmup problem.
Solution for parts 1 and 2
package main
import (
"bufio"
"embed"
_ "embed"
"fmt"
"log"
"sort"
"strconv"
)
//go:embed input.txt input-ex.txt
var inputFiles embed.FS
func main() {
nums := ReadInput()
part1(nums)
part2(nums)
}
func part1(elves [][]int) {
maxTotalCals := 0
for _, elf := range elves {
totalCals := 0
for _, cals := range elf {
totalCals += cals
}
if totalCals > maxTotalCals {
maxTotalCals = totalCals
}
}
fmt.Println(maxTotalCals)
}
func part2(elves [][]int) {
totalCals := make([]int, len(elves))
for i, elf := range elves {
for _, cals := range elf {
totalCals[i] += cals
}
}
sort.Ints(totalCals)
sum := 0
sum += totalCals[len(totalCals)-1]
sum += totalCals[len(totalCals)-2]
sum += totalCals[len(totalCals)-3]
fmt.Println(sum)
}
func ReadInput() [][]int {
f, err := inputFiles.Open("input.txt")
if err != nil {
log.Fatal(err)
}
var nums [][]int
nums = append(nums, []int{})
scanner := bufio.NewScanner(f)
for scanner.Scan() {
line := scanner.Text()
if line == "" {
nums = append(nums, []int{})
} else {
n, err := strconv.Atoi(line)
if err != nil {
panic("nope")
}
nums[len(nums)-1] = append(nums[len(nums)-1], n)
}
}
return nums
}
Go embed
When running main
in GoLand there’s a small annoying problem where the working directory is set automatically to the go.mod
directory instead of the location of the .go
file. This means that most of my first runs last year resulted in input.txt was not found
.
By using the embed
package the input file is compiled into the binary, and I can refer to it relatively to the current file. It’s not as clean as just reading stdin
or the first argument, but it saves me 30 seconds every day, which could mean the difference between leaderboard or not.