Advent of Code 2022: Day1

Back up

Stream Video

Code

package aoc

import (
	"fmt"
	"io"
	"sort"
	"strconv"

	"mono3/advent/lib/lineio"
	"mono3/common/log"
	"mono3/common/tty"
)

type elf struct {
	cals int
}

type byCals []*elf

func (b byCals) Len() int           { return len(b) }
func (b byCals) Less(i, j int) bool { return b[i].cals < b[j].cals }
func (b byCals) Swap(i, j int)      { b[i], b[j] = b[j], b[i] }

// Each part gets the same input with reader pointing at the start of input.
var PuzzleParts = []func(r io.Reader) error{
	PuzzlePart1,
	PuzzlePart2,
}

func PuzzlePart1(r io.Reader) error {
	return solveit(r, 1)
}

func PuzzlePart2(r io.Reader) error {
	return solveit(r, 3)
}

func solveit(r io.Reader, topk int) error {
	log.Info("Running")

	var elves []*elf
	curElf := &elf{}

	if err := lineio.ForEachWithBlanks(r, func(ln int, line string) error {
		if line == "" {
			elves = append(elves, curElf)
			curElf = &elf{}
			return nil
		}

		num, err := strconv.ParseInt(line, 10, 64)
		if err != nil {
			return fmt.Errorf("invalid number line %d: %w", ln, err)
		}
		curElf.cals += int(num)

		return nil
	}); err != nil {
		return err
	}

	sort.Sort(byCals(elves))
	total := 0
	for i := len(elves) - 1; i > len(elves)-1-topk; i-- {
		total += elves[i].cals
	}

	tty.Printf("Sorted elves, top %d elf has %d\n", topk, total)

	return nil
}

aimeeble@blog

the blog of aimeeble


By Aimee, 2022-12-01


Table of Contents: