-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaoc19_day5.R
92 lines (73 loc) · 3.09 KB
/
aoc19_day5.R
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
## Advent of Code 2019, Day 5
## https://adventofcode.com/2019/day/5
##
## Author: Maarten Demeyer <mpjdem@gmail.com>
## GitHub: https://github.com/mpjdem
## Website: https://www.mpjdem.xyz
## Get the test program
mmry <- as.numeric(strsplit(readLines("input/input5.txt"), ",")[[1]])
## Solution for both parts of the assignment, modifying my Day 2 solution
run_intcode <- function(inp, mmry) {
ptr <- 1
repeat({
## Parse opcode, parameter modes and parameters from the instruction
parmodes_opcode <- mmry[ptr]
opcode <- as.character(parmodes_opcode %% 100)
n_params <- switch(opcode,
"1" = 3, "2" = 3, "3" = 1, "4" = 1,
"5" = 2, "6" = 2, "7" = 3, "8" = 3,
"99" = 0)
parmodes <- sapply(10 ** (seq_len(n_params) + 1),
function(x) floor(parmodes_opcode / x) %% 10)
params <- mmry[ptr+seq_len(n_params)]
## Function to retrieve the value of parameter N, depending on mode
## Do not use for write positions, those are directly given as positions
get_val <- function(parn) {
if (parmodes[parn] == 1) params[parn] else mmry[params[parn] + 1]
}
## Perform the operation according to the instruction
next_instruction_ptr <- ptr + n_params + 1
ptr <-
if (opcode == "1") {
mmry[params[3] + 1] <- get_val(1) + get_val(2)
next_instruction_ptr
} else if (opcode == "2") {
mmry[params[3] + 1] <- get_val(1) * get_val(2)
next_instruction_ptr
} else if (opcode == "3") {
mmry[params[1] + 1] <- inp
next_instruction_ptr
} else if(opcode == "4") {
output <<- c(output, get_val(1))
next_instruction_ptr
} else if (opcode == "5") {
if (get_val(1) != 0) get_val(2) + 1 else next_instruction_ptr
} else if (opcode == "6") {
if (get_val(1) == 0) get_val(2) + 1 else next_instruction_ptr
} else if (opcode == "7") {
mmry[params[3] + 1] <- as.numeric(get_val(1) < get_val(2))
next_instruction_ptr
} else if (opcode == "8") {
mmry[params[3] + 1] <- as.numeric(get_val(1) == get_val(2))
next_instruction_ptr
}
## Stop if we encounter opcode 99 or when we reach the end
if (opcode == "99" || ptr > length(mmry)) {
break
}
})
}
## -- PART 1 --
output <- numeric(0)
final_mmry <- run_intcode(1, mmry)
solution_1 <- tail(output, 1)
cat("Solution to Part 1:", solution_1, "- ")
check_1 <- as.numeric(readLines("output/output5_1.txt"))
if (check_1 == solution_1) cat("correct!\n") else cat("wrong!\n")
## -- PART 2 --
output <- numeric(0)
final_mmry <- run_intcode(5, mmry)
solution_2 <- tail(output, 1)
cat("Solution to Part 2:", solution_2, "- ")
check_2 <- as.numeric(readLines("output/output5_2.txt"))
if (check_2 == solution_2) cat("correct!\n") else cat("wrong!\n")