|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "strings" |
| 6 | + |
| 7 | + "github.com/believer/aoc-utils/files" |
| 8 | +) |
| 9 | + |
| 10 | +// Pretty simple DP solution. Nice breather after yesterday. |
| 11 | +// The thing I didn't know was how to create a good cache |
| 12 | +// representation for multiple values and recursion. So, I |
| 13 | +// (actually) asked Gemini about how to solve that part. |
| 14 | + |
| 15 | +func main() { |
| 16 | + fmt.Println("Part 1: ", part1("input.txt")) |
| 17 | + fmt.Println("Part 2: ", part2("input.txt")) |
| 18 | +} |
| 19 | + |
| 20 | +func part1(name string) int { |
| 21 | + paths := createPaths(name) |
| 22 | + |
| 23 | + // DAC and FFT are not needed in part 1, set to true |
| 24 | + return countPaths(paths, "you", true, true) |
| 25 | +} |
| 26 | + |
| 27 | +func part2(name string) int { |
| 28 | + paths := createPaths(name) |
| 29 | + |
| 30 | + return countPaths(paths, "svr", false, false) |
| 31 | +} |
| 32 | + |
| 33 | +type cacheKey struct { |
| 34 | + from string |
| 35 | + dac bool |
| 36 | + fft bool |
| 37 | +} |
| 38 | + |
| 39 | +func countPaths(paths map[string][]string, start string, dac, fft bool) int { |
| 40 | + cache := make(map[cacheKey]int) |
| 41 | + |
| 42 | + var solve func(from string, dac, fft bool) int |
| 43 | + |
| 44 | + solve = func(from string, dac, fft bool) int { |
| 45 | + key := cacheKey{from, dac, fft} |
| 46 | + |
| 47 | + if result, ok := cache[key]; ok { |
| 48 | + return result |
| 49 | + } |
| 50 | + |
| 51 | + switch from { |
| 52 | + case "out": |
| 53 | + // Has visited both DAC and FFT |
| 54 | + if dac && fft { |
| 55 | + return 1 |
| 56 | + } |
| 57 | + return 0 |
| 58 | + case "dac": |
| 59 | + dac = true |
| 60 | + case "fft": |
| 61 | + fft = true |
| 62 | + } |
| 63 | + |
| 64 | + sum := 0 |
| 65 | + |
| 66 | + for _, to := range paths[from] { |
| 67 | + sum += solve(to, dac, fft) |
| 68 | + } |
| 69 | + |
| 70 | + cache[key] = sum |
| 71 | + |
| 72 | + return sum |
| 73 | + } |
| 74 | + |
| 75 | + return solve(start, dac, fft) |
| 76 | +} |
| 77 | + |
| 78 | +// Create a map of all devices and their outputs |
| 79 | +func createPaths(name string) map[string][]string { |
| 80 | + lines := files.ReadLines(name) |
| 81 | + paths := map[string][]string{} |
| 82 | + |
| 83 | + for _, l := range lines { |
| 84 | + device, outputs, _ := strings.Cut(l, ": ") |
| 85 | + |
| 86 | + paths[device] = strings.Fields(outputs) |
| 87 | + } |
| 88 | + |
| 89 | + return paths |
| 90 | +} |
0 commit comments