Skip to content

Instantly share code, notes, and snippets.

@ursulams
Created December 12, 2024 03:41
Show Gist options
  • Select an option

  • Save ursulams/53cde613d890ea5f5e9ce0b762384ae8 to your computer and use it in GitHub Desktop.

Select an option

Save ursulams/53cde613d890ea5f5e9ce0b762384ae8 to your computer and use it in GitHub Desktop.
2024 advent of code day 6
# first star
input <- as.matrix(read.fwf("input.txt", widths = rep(1, 130), comment.char = ""))
# pad to indicate exit
#input <- rbind("E", cbind("E", input, "E"), "E")
starting <- as.vector(which(input == "^", arr.ind = TRUE)[1,])
# function moves n,m position in matrix
step <- function(direction, mode){
coords <- list(c(-1, 0), c(1, 0), c(0, 1), c(0, -1))
mode == "unblocked"
if(mode == "unblocked"){
switch(direction, "^" = coords[[1]], "v" = coords[[2]], ">" = coords[[3]], "<" = coords[[4]])
}
else {mode == "blocked"
switch(direction, "^" = ">", "v" = "<", ">" = "v", "<" = "^")
}
}
# log steps in list
steps <- list(starting)
# starting from up
direction <- "^"
# move, log steps until blocked, then change mode to new move
while(starting[1] > 1 & starting[1] < 130 & starting[2] > 1 & starting[2] < 130){
next_step <- starting + step(direction, "unblocked")
if(input[next_step[1], next_step[2]] != "#"){
steps[[length(steps) + 1]] <- paste(starting, collapse = ",")
starting <- starting + step(direction, "unblocked")
}
else{
steps[[length(steps) + 1]] <- paste(starting, collapse = ",")
direction <- step(direction, "blocked")
}
}
length(steps[which(!duplicated(steps))]) # count not-retraced steps beyond start
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment