── Attaching packages ─────────────────────────────────────── tidyverse 1.3.2 ──
✔ ggplot2 3.4.0 ✔ purrr 0.3.5
✔ tibble 3.1.8 ✔ dplyr 1.0.10
✔ tidyr 1.2.1 ✔ stringr 1.4.1
✔ readr 2.1.3 ✔ forcats 0.5.2
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag() masks stats::lag()
06: Probably a Fire Hazard
Warning in readLines("input.txt"): incomplete final line found on 'input.txt'
Part 1
dt <- data.frame("dir" = str_extract(dt, "off|on|toggle"),
"from" = str_extract(dt, "[0-9]{1,3},[0-9]{1,3}"),
"to" = str_extract(dt, "[0-9]{1,3},[0-9]{1,3}$"))
from <- str_split(dt$from, ",", simplify = TRUE)
dt$fromX <- as.numeric(from[,1]) + 1
dt$fromY <- as.numeric(from[,2]) + 1
to <- str_split(dt$to, ",", simplify = TRUE)
dt$toX <- as.numeric(to[,1]) + 1
dt$toY <- as.numeric(to[,2]) + 1
lights <- data.frame("x" = rep(1:1000, 1000),
"y" = rep(1:1000, each = 1000),
"stat" = as.integer(0))
for(i in 1:nrow(dt)) {
if(dt$dir[i] == "on") {
lights$stat[dt$fromX[i] <= lights$x &
dt$toX[i] >= lights$x &
dt$fromY[i] <= lights$y &
dt$toY[i] >= lights$y] <- 1
}
if(dt$dir[i] == "off") {
lights$stat[dt$fromX[i] <= lights$x &
dt$toX[i] >= lights$x &
dt$fromY[i] <= lights$y &
dt$toY[i] >= lights$y] <- 0
}
if(dt$dir[i] == "toggle") {
lights$stat[dt$fromX[i] <= lights$x & dt$toX[i] >= lights$x &
dt$fromY[i] <= lights$y & dt$toY[i] >= lights$y] <-
ifelse(lights$stat[dt$fromX[i] <= lights$x & dt$toX[i] >= lights$x &
dt$fromY[i] <= lights$y & dt$toY[i] >= lights$y] == 1, 0, 1)
}
}
nrow(lights[lights$stat == 1,])
[1] 400410
Part 2
# part 2
lights <- data.frame("x" = rep(1:1000, 1000),
"y" = rep(1:1000, each = 1000),
"stat" = as.integer(0))
for(i in 1:nrow(dt)) {
if(dt$dir[i] == "on") {
lights$stat[dt$fromX[i] <= lights$x &
dt$toX[i] >= lights$x &
dt$fromY[i] <= lights$y &
dt$toY[i] >= lights$y] <- lights$stat[dt$fromX[i] <= lights$x &
dt$toX[i] >= lights$x &
dt$fromY[i] <= lights$y &
dt$toY[i] >= lights$y] + 1
}
if(dt$dir[i] == "off") {
lights$stat[dt$fromX[i] <= lights$x & dt$toX[i] >= lights$x &
dt$fromY[i] <= lights$y & dt$toY[i] >= lights$y] <-
ifelse(lights$stat[dt$fromX[i] <= lights$x & dt$toX[i] >= lights$x &
dt$fromY[i] <= lights$y & dt$toY[i] >= lights$y] == 0,
lights$stat[dt$fromX[i] <= lights$x & dt$toX[i] >= lights$x &
dt$fromY[i] <= lights$y & dt$toY[i] >= lights$y],
lights$stat[dt$fromX[i] <= lights$x & dt$toX[i] >= lights$x &
dt$fromY[i] <= lights$y & dt$toY[i] >= lights$y] - 1)
}
if(dt$dir[i] == "toggle") {
lights$stat[dt$fromX[i] <= lights$x &
dt$toX[i] >= lights$x &
dt$fromY[i] <= lights$y &
dt$toY[i] >= lights$y] <- lights$stat[dt$fromX[i] <= lights$x &
dt$toX[i] >= lights$x &
dt$fromY[i] <= lights$y &
dt$toY[i] >= lights$y] + 2
}
}
sum(lights$stat)
[1] 15343601