|
| 1 | +// --- Day 2: 1202 Program Alarm --- |
| 2 | +// https://adventofcode.com/2019/day/2 |
| 3 | +package main |
| 4 | + |
| 5 | +import ( |
| 6 | + "bufio" |
| 7 | + "log" |
| 8 | + "os" |
| 9 | + |
| 10 | + "github.com/alkurbatov/adventofcode/internal/parsers" |
| 11 | +) |
| 12 | + |
| 13 | +func readInput(path string) ([]int, error) { |
| 14 | + input, err := os.Open(path) |
| 15 | + if err != nil { |
| 16 | + return nil, err |
| 17 | + } |
| 18 | + defer input.Close() |
| 19 | + |
| 20 | + scanner := bufio.NewScanner(input) |
| 21 | + scanner.Scan() |
| 22 | + |
| 23 | + if err := scanner.Err(); err != nil { |
| 24 | + return nil, err |
| 25 | + } |
| 26 | + |
| 27 | + return parsers.ReadNumbers(scanner.Text(), ",") |
| 28 | +} |
| 29 | + |
| 30 | +func runIntcode(program []int) int { |
| 31 | + i := 0 |
| 32 | + |
| 33 | + for i < len(program) { |
| 34 | + instruction := program[i] |
| 35 | + |
| 36 | + if instruction == 99 { |
| 37 | + break |
| 38 | + } |
| 39 | + |
| 40 | + p1 := program[i+1] |
| 41 | + p2 := program[i+2] |
| 42 | + p3 := program[i+3] |
| 43 | + |
| 44 | + switch instruction { |
| 45 | + case 1: |
| 46 | + program[p3] = program[p1] + program[p2] |
| 47 | + case 2: |
| 48 | + program[p3] = program[p1] * program[p2] |
| 49 | + } |
| 50 | + |
| 51 | + i += 4 |
| 52 | + } |
| 53 | + |
| 54 | + return program[0] |
| 55 | +} |
| 56 | + |
| 57 | +func restoreGravityAssist(program []int) int { |
| 58 | + programCopy := append([]int(nil), program...) |
| 59 | + |
| 60 | + // Apply rules |
| 61 | + programCopy[1] = 12 // noun |
| 62 | + programCopy[2] = 2 // verb |
| 63 | + |
| 64 | + return runIntcode(programCopy) |
| 65 | +} |
| 66 | + |
| 67 | +func completeGravityAssist(program []int) (noun, verb int) { |
| 68 | + for noun = 0; noun < 100; noun++ { |
| 69 | + for verb = 0; verb < 100; verb++ { |
| 70 | + programCopy := append([]int(nil), program...) |
| 71 | + |
| 72 | + // Apply rules |
| 73 | + programCopy[1] = noun |
| 74 | + programCopy[2] = verb |
| 75 | + |
| 76 | + if runIntcode(programCopy) == 19690720 { |
| 77 | + return noun, verb |
| 78 | + } |
| 79 | + } |
| 80 | + } |
| 81 | + |
| 82 | + return noun, verb |
| 83 | +} |
| 84 | + |
| 85 | +func main() { |
| 86 | + program, err := readInput("./2019/2/input.txt") |
| 87 | + if err != nil { |
| 88 | + log.Printf("Failed to read data from input.txt: %v", err) |
| 89 | + return |
| 90 | + } |
| 91 | + |
| 92 | + firstPartResult := restoreGravityAssist(program) |
| 93 | + log.Printf("Part 1 result: %d", firstPartResult) |
| 94 | + |
| 95 | + noun, verb := completeGravityAssist(program) |
| 96 | + secondPartResult := 100*noun + verb |
| 97 | + log.Printf("Part 2 result: %d", secondPartResult) |
| 98 | +} |
0 commit comments