102 lines
1.8 KiB
Go
102 lines
1.8 KiB
Go
package day11
|
|
|
|
import (
|
|
"fmt"
|
|
"strings"
|
|
|
|
"git.bizdoc.ro/gabi-public/Advent-of-Code.git/aoc"
|
|
"git.bizdoc.ro/private/devkit.git/collections/dsa"
|
|
)
|
|
|
|
func parseInput(ctx aoc.Context) (map[string][]string, error) {
|
|
graph := make(map[string][]string)
|
|
|
|
s := ctx.Scanner()
|
|
for s.Scan() {
|
|
line := s.Text()
|
|
parts := strings.Split(line, ": ")
|
|
key := parts[0]
|
|
graph[key] = strings.Split(parts[1], " ")
|
|
}
|
|
if err := s.Err(); err != nil {
|
|
return nil, fmt.Errorf("scanner error: %w", err)
|
|
}
|
|
return graph, nil
|
|
}
|
|
|
|
func Part1(ctx aoc.Context) (int, error) {
|
|
graph, err := parseInput(ctx)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
|
|
const start = "you"
|
|
const end = "out"
|
|
|
|
stack := dsa.NewStack[string]()
|
|
stack.Push(start)
|
|
var pathsToEnd int
|
|
for !stack.IsEmpty() {
|
|
this := stack.Pop()
|
|
for _, next := range graph[this] {
|
|
stack.Push(next)
|
|
}
|
|
if this == end {
|
|
pathsToEnd += 1
|
|
}
|
|
}
|
|
|
|
return pathsToEnd, nil
|
|
}
|
|
|
|
func Part2(ctx aoc.Context) (uint64, error) {
|
|
graph, err := parseInput(ctx)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
|
|
type Item struct {
|
|
DAC, FFT bool
|
|
Name string
|
|
}
|
|
cache := make(map[Item]uint64)
|
|
|
|
var recursion func(current Item, end string) uint64
|
|
recursion = func(current Item, end string) uint64 {
|
|
if current.Name == end {
|
|
return bool2int(current.DAC && current.FFT)
|
|
}
|
|
|
|
switch current.Name {
|
|
case "dac":
|
|
current.DAC = true
|
|
case "fft":
|
|
current.FFT = true
|
|
}
|
|
|
|
var sum uint64
|
|
for _, next := range graph[current.Name] {
|
|
current.Name = next
|
|
|
|
paths, ok := cache[current]
|
|
if !ok {
|
|
paths = recursion(current, end)
|
|
cache[current] = paths
|
|
}
|
|
sum += paths
|
|
}
|
|
return sum
|
|
}
|
|
return recursion(Item{DAC: false, FFT: false, Name: "svr"}, "out"), nil
|
|
}
|
|
|
|
func bool2int(b bool) uint64 {
|
|
var i uint64
|
|
if b {
|
|
i = 1
|
|
} else {
|
|
i = 0
|
|
}
|
|
return i
|
|
}
|