-
Notifications
You must be signed in to change notification settings - Fork 3
/
day02.go
119 lines (105 loc) · 2.06 KB
/
day02.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
// Package main provides ...
package main
import (
"bufio"
"fmt"
"log"
"os"
"strconv"
"strings"
)
var (
OP_ADD = 1
OP_MULT = 2
OP_STOP = 99
)
func Parse(filename string) []int {
file, err := os.Open(filename)
if err != nil {
log.Fatal(err)
}
var strNums []string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
strNums = strings.Split(line, ",")
break
}
nums := make([]int, 0)
for _, thisStrNum := range strNums {
thisNum, err := strconv.Atoi(strings.TrimSpace(thisStrNum))
if err != nil {
log.Fatal(err)
}
nums = append(nums, thisNum)
}
return nums
}
func Compute(program []int) []int {
i := 0
isRunning := true
for isRunning {
instruction := program[i]
switch instruction {
case OP_ADD:
// fmt.Println("add")
posIn1 := program[i+1]
posIn2 := program[i+2]
posOut := program[i+3]
program[posOut] = program[posIn1] + program[posIn2]
i += 4
case OP_MULT:
// fmt.Println("multiply")
posIn1 := program[i+1]
posIn2 := program[i+2]
posOut := program[i+3]
program[posOut] = program[posIn1] * program[posIn2]
i += 4
case OP_STOP:
isRunning = false
default:
log.Fatal("Unknown Instruction")
}
}
return program
}
func Part1(program []int) int {
program = CloneProgram(program)
program[1] = 12
program[2] = 2
program = Compute(program)
return program[0]
}
func Part2(program []int) int {
for i := 0; i < 100; i++ {
for j := 0; j < 100; j++ {
if Part2Eval(program, i, j) == 19690720 {
return Part2Answer(i, j)
}
}
}
return 0
}
func Part2Eval(program []int, noun int, verb int) int {
program = CloneProgram(program)
program[1] = noun
program[2] = verb
program = Compute(program)
return program[0]
}
func Part2Answer(noun int, verb int) int {
return 100*noun + verb
}
func CloneProgram(program []int) []int {
x := make([]int, len(program))
copy(x, program)
return x
}
func main() {
nums := Parse("../input.txt")
fmt.Println("AOC 2019 Day 02:")
fmt.Println("Part 1:")
fmt.Println(Part1(nums))
fmt.Println("Part2:")
fmt.Println(Part2(nums))
}