-
Notifications
You must be signed in to change notification settings - Fork 0
/
day14.R
67 lines (52 loc) · 2.12 KB
/
day14.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
# Decription of script ---------------------------------------------------------
# Day 14 advent of code --Docking Data
# ------------------------------------------------------------------------------
# set up -----------------------------------------------------------------------
library(tidyverse)
# load data --------------------------------------------------------------------
program <- read_delim('day14.txt', col_names = FALSE, delim = " = ") %>%
select(instruction = X1, value = X3)
# solve the puzzle -------------------------------------------------------------
# part 1
memory <- array()
for (i in 1:nrow(program)){
if(program$instruction[i] == "mask"){
mask <- program$value[i] # change the mask to be the new mask
} else{
bits <- c(rep(as.raw(0), 4), rev(intToBits(as.integer(program$value[i])))) # convert to bits
for (j in 1:nchar(mask)){
if (substr(mask,j,j) %in% c(1,0)){
bits[j] <- as.raw(substr(mask,j,j))
}
}
memory[parse_number(program$instruction[i])] <- sum(as.numeric(bits) * 2^seq(35,0))
}
}
sum(memory, na.rm = TRUE)
# part 2
memory <- data.frame(location = NA, value = NA)
for (i in 1:nrow(program)){
if(program$instruction[i] == "mask"){
mask <- program$value[i] # change the mask to be the new mask
} else{
bits <- c(rep(as.raw(0), 4), rev(intToBits(as.integer(parse_number(program$instruction[i]))))) # convert to bits
change_bit <- NULL
for (j in 1:nchar(mask)){
if (substr(mask,j,j) == 1){
bits[j] <- as.raw(substr(mask,j,j))
} else if (substr(mask,j,j) == "X"){
change_bit <- c(change_bit,j)
}
}
all_change_combo <- expand.grid(rep( list( 0:1 ), length(change_bit)))
for (k in 1:nrow(all_change_combo)){
bits[change_bit] <- as.raw(all_change_combo[k,])
if(length(which(memory$location == (sum(as.numeric(bits) * 2^seq(35,0))))) == 0){
memory <- rbind(memory, c((sum(as.numeric(bits) * 2^seq(35,0))), program$value[i]))
} else {
memory[which(memory$location == (sum(as.numeric(bits) * 2^seq(35,0)))),]$value <- program$value[i]
}
}
}
}
sum(as.numeric(memory), na.rm = TRUE)