Advent of Code 2022: Day2

Back up

Stream Video

Code

package aoc

import (
	"fmt"
	"io"
	"strings"

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

const (
	meRock    = "X"
	mePaper   = "Y"
	meScissor = "Z"
)

var shapeToScore = map[string]int{
	"A":       0,
	"B":       0,
	"C":       0,
	meRock:    1,
	mePaper:   2,
	meScissor: 3,
}

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

func pointsFromRound(them, me string) int {
	if them == "A" {
		switch me { // rock
		case meRock:
			// tie
			return 3
		case mePaper:
			// win
			return 6
		case meScissor:
			// lose
			return 0
		}
	} else if them == "B" { // paper
		switch me {
		case "X": // rock
			// lose
			return 0
		case "Y": // paper
			// tie
			return 3
		case "Z": // scissor
			// win
			return 6
		}
	} else if them == "C" { // scissor
		switch me {
		case "X": // rock
			// win
			return 6
		case "Y": // paper
			// lose
			return 0
		case "Z": // scissor
			// tie
			return 3
		}
	}

	// ????
	return 0
}

func PuzzlePart1(r io.Reader) error {
	return solveit(r, func(them, me string) int {
		return shapeToScore[me] + pointsFromRound(them, me)
	})
}

func PuzzlePart2(r io.Reader) error {
	return solveit(r, func(them, outcome string) int {
		// map from them-outcome -> what I should do.
		lookup := map[string]string{
			"AX": "Z",
			"AY": "X",
			"AZ": "Y",

			"BX": "X",
			"BY": "Y",
			"BZ": "Z",

			"CX": "Y",
			"CY": "Z",
			"CZ": "X",
		}

		me := lookup[fmt.Sprintf("%s%s", them, outcome)]
		total := shapeToScore[me] + pointsFromRound(them, me)
		//tty.Printf("round n: %s vs %s = %d + %d = %d\n",
		//	them, me,
		//	shapeToScore[me], pointsFromRound(them, me),
		//	total,
		//)
		return total
	})
}

func solveit(r io.Reader, calc func(a, b string) int) error {
	totalScore := 0
	if err := lineio.ForEach(r, func(ln int, line string) error {
		parts := strings.SplitN(line, " ", 2)
		a := parts[0]
		b := parts[1]

		totalScore += calc(a, b)

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

	tty.Printf("Total score: %d\n", totalScore)

	return nil
}

aimeeble@blog

the blog of aimeeble


By Aimee, 2022-12-02


Table of Contents: