-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday10.go
80 lines (58 loc) · 1.52 KB
/
day10.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
package day10
import (
"strconv"
"strings"
)
type Instruction struct {
command string
argument int
}
func parseInstructions(input string) (instructions []Instruction) {
for _, rawInstruction := range strings.Split(input, "\n") {
instructionParts := strings.Split(rawInstruction, " ")
if instructionParts[0] == "noop" {
instructions = append(instructions, Instruction{instructionParts[0], 0})
continue
}
numericArgument, err := strconv.Atoi(instructionParts[1])
if err != nil {
panic("Error converting argument to int")
}
instructions = append(instructions, Instruction{instructionParts[0], numericArgument})
}
return
}
func runProgram(instructions []Instruction, cyclesToRun int) int {
x := 1
instructionPointer := 0
var pendingInstruction Instruction
workingUntil := -1
for cycle := 0; cycle < cyclesToRun; cycle++ {
if pendingInstruction.command != "" {
if cycle < workingUntil {
continue
}
x += pendingInstruction.argument
instructionPointer++
pendingInstruction = Instruction{}
}
instruction := instructions[instructionPointer]
if instruction.command == "noop" {
instructionPointer++
continue
}
if instruction.command == "addx" {
pendingInstruction = instruction
workingUntil = cycle + 2
}
}
return x
}
func part1(input string) (result int) {
instructions := parseInstructions(input)
cycleRuns := []int{20, 60, 100, 140, 180, 220}
for _, cyclesToRun := range cycleRuns {
result += runProgram(instructions, cyclesToRun) * cyclesToRun
}
return
}