-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
87 lines (69 loc) · 1.59 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package main
import (
"github.com/sanderploegsma/advent-of-code/2019/go/utils"
"log"
"strconv"
)
func main() {
program, err := parseProgram("input.txt")
if err != nil {
log.Fatalf("unable to read file: %v", err)
}
log.Printf("[PART ONE] result: %v", RunProgramWithInput(program, 12, 2))
noun, verb := FindNounAndVerb(program, 19690720)
log.Printf("[PART TWO] result: 100 * %d + %d = %d", noun, verb, 100*noun+verb)
}
func RunProgram(program []int) []int {
return RunProgramWithInput(program, program[1], program[2])
}
func RunProgramWithInput(program []int, noun, verb int) []int {
result := make([]int, len(program))
for i := range program {
result[i] = program[i]
}
result[1] = noun
result[2] = verb
index := 0
for index <= len(result)-1 {
opcode := result[index]
if opcode == 99 {
break
}
x := result[result[index+1]]
y := result[result[index+2]]
pos := result[index+3]
if opcode == 1 {
result[pos] = x + y
}
if opcode == 2 {
result[pos] = x * y
}
index += 4
}
return result
}
func FindNounAndVerb(program []int, outcome int) (noun int, verb int) {
for noun := 0; noun < 100; noun++ {
for verb := 0; verb < 100; verb++ {
result := RunProgramWithInput(program, noun, verb)
if result[0] == outcome {
return noun, verb
}
}
}
return noun, verb
}
func parseProgram(file string) (input []int, err error) {
items, err := utils.ReadDelim(file, ",")
if err != nil {
return nil, err
}
for _, item := range items {
val, err := strconv.Atoi(item)
if err != nil {
return nil, err
}
input = append(input, val)
}
return input, err
}