Created
December 10, 2024 04:35
-
-
Save ursulams/7c69db3a3cad3ad5e95f898ecffd7844 to your computer and use it in GitHub Desktop.
2024 advent of code day 5
This file contains hidden or 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
# first star | |
input <- readLines("input.txt") | |
pages <- as.data.frame(t(sapply(strsplit(input[grep("\\|", input)], "\\|"), as.integer))) | |
updates <- lapply(strsplit(input[grep(",", input)], ","), as.integer) | |
get_order <- function(u){ | |
ordered <- pages[(pages$V1 %in% u) & (pages$V2 %in% u), ] # which page pairs apply to update | |
ordered$V1_idx <- sapply(ordered$V1, function(x){which(u == x)}) # get indices | |
ordered$V2_idx <- sapply(ordered$V2, function(x){which(u == x)}) | |
ordered$check <- (ordered$V1_idx < ordered$V2_idx) # check if indices in correct order | |
ordered <- all(ordered$check) | |
if (ordered){return(u[ceiling(length(u)/2)])} # return midpoint value | |
else {return(0)} | |
} | |
sum(sapply(updates, get_order)) | |
# second star | |
# isolate the pages left to update | |
order_up <- function(u){ | |
if(get_order(u)){return(0)} | |
else{return(u)} | |
} | |
to_update <- Filter(function(x){is.integer(x)}, sapply(updates, order_up)) | |
# table sort idea + application courtesy of u/cettbycett | |
check_order <- function(u) { | |
pages <- t(pages) | |
to_order <- pages[ ,apply(pages, 2, function(z) sum(u %in% z) == 2)] | |
ordered <- as.integer(names(sort(-table(to_order[1, ])))) | |
ordered <- c(ordered, setdiff(u, to_order[1,])) | |
ordered[ceiling(length(u)/2)] * if (identical(ordered, u)) 1 else -1 | |
} | |
ordered <- sapply(to_update, check_order) | |
sum(-ordered[ordered < 0]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment