-
Notifications
You must be signed in to change notification settings - Fork 1
/
day08.Rmd
86 lines (82 loc) · 1.64 KB
/
day08.Rmd
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
---
title: "--- Day 8: Handheld Halting ---"
author: Fleur Kelpin
date: Dec 8, 2020
output: github_document
---
```{r message=FALSE, warning=FALSE}
library(tidyverse)
input <- readr::read_lines("day08.txt") %>%
tibble(instruction=.)
input
```
# Part 1
First let's parse the instructions.
```{r}
program <- input %>%
extract(instruction,
into=c("operation", "argument"),
regex="(\\w+) ([+-]\\d+)",
convert = TRUE)
program
```
Then implement the instructions
```{r}
state <- list(acc=0, ip=0)
nop <- function(acc, ip) {
list(acc = acc, ip = ip + 1)
}
acc <- function(arg, acc, ip) {
list(acc = acc + arg, ip = ip + 1)
}
jmp <- function(arg, acc, ip) {
list(acc = acc, ip = ip + arg)
}
step <- function(program, s) {
op <- program$operation[[s$ip + 1]]
arg <- program$argument[[s$ip + 1]]
switch(op,
"nop" = nop(s$acc, s$ip),
"acc" = acc(arg, s$acc, s$ip),
"jmp" = jmp(arg, s$acc, s$ip)
)
}
step(program, state)
```
Then we're ready to solve part 1:
```{r}
findLoop <- function(program) {
state <- list(acc=0, ip=0)
visited <- c()
while(!state$ip %in% visited) {
visited <- append(visited, state$ip)
if (state$ip > nrow(program)-1) {
print("Terminated!")
print(state)
return(state)
}
state <- step(program, state)
}
state
}
findLoop(program)
```
# Part 2
```{r error=FALSE}
fix <- function (program, i) {
op <- program$operation[[i]]
fixed <- program
if (op == 'jmp'){
fixed$operation[[i]] = 'nop'
}
if (op == 'nop'){
fixed$operation[[i]] = 'jmp'
}
fixed
}
for(i in 1:nrow(program)) {
program %>%
fix(i) %>%
findLoop
}
```