Created
December 7, 2024 01:07
-
-
Save czep/ba6d4a19d5e7badd8636cbd33eb0d1cf to your computer and use it in GitHub Desktop.
AoC 2024 Day 6
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### | |
### Day 6 | |
### | |
### Part 1 | |
### concise version, don't bother checking for matrix bounds! | |
library(tidyverse) | |
input <- read_lines("day6_input.txt") | |
m <- str_split_fixed(input, pattern = "", n = str_length(input[1])) | |
pos <- which(m=="^", arr.ind=TRUE) | |
directions <- matrix(c(-1,0, 0,1, 1,0, 0,-1), nrow = 4, ncol = 2, byrow=TRUE) | |
move <- 1 | |
while (1) { | |
m[pos] <- "X" | |
nextpos <- pos + directions[move, 1:2] | |
while (m[nextpos] == "#") { | |
move <- move + 1 | |
if (move > 4) move <- 1 | |
nextpos <- pos + directions[move, 1:2] | |
} | |
pos <- nextpos | |
} | |
table(m) | |
# m | |
# . # X | |
# 11379 810 4711 | |
### Part 2 | |
### Yet Another Brute Force! | |
inbounds <- function(x) { | |
if (x[1,1] > 0 & x[1,2] > 0 & x[1,1] <= dim(m)[1] & x[1,2] <= dim(m)[2]) return(TRUE) | |
return(FALSE) | |
} | |
m0 <- str_split_fixed(input, pattern = "", n = str_length(input[1])) | |
loops <- 0 | |
for (i in 1:length(m0)) { | |
if (m0[i] %in% c("#", "^")) next | |
m <- m0 | |
m[i] <- "#" | |
pos <- which(m=="^", arr.ind=TRUE) | |
move <- 1 | |
while (inbounds(pos)) { | |
if (m[pos] %in% c(".", "^")) m[pos] <- 0 | |
m[pos] <- as.numeric(m[pos]) + 1 | |
nextpos <- pos + directions[move, 1:2] | |
while (inbounds(nextpos) && m[nextpos] == "#") { | |
move <- move + 1 | |
if (move > 4) move <- 1 | |
nextpos <- pos + directions[move, 1:2] | |
} | |
if (as.numeric(m[pos]) >= 10) { | |
loops <- loops + 1 | |
break | |
} | |
pos <- nextpos | |
} | |
if (i %% 100 == 0) print(c(i, loops)) | |
} | |
loops | |
# [1] 1562 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment