Skip to content

Instantly share code, notes, and snippets.

@mathesong
Created December 2, 2024 10:35
Show Gist options
  • Save mathesong/78636de9e1e87b94eadb1b4572e7128c to your computer and use it in GitHub Desktop.
Save mathesong/78636de9e1e87b94eadb1b4572e7128c to your computer and use it in GitHub Desktop.
Advent of Code 2024: Day 2
library(tidyverse)
input <- read_delim("input", delim="\t", col_names = "d")
##### Part 1 #####
report_safe <- function(report) {
vals <- as.numeric(str_split(report, " ")[[1]])
difs <- diff(vals)
if( all(difs < 0) | all(difs > 0) ) {
absdifs <- abs(difs)
if( all(absdifs > 0) & all(absdifs < 4) ) {
return(TRUE)
}
}
return(FALSE)
}
# rowwise causing issues here, so I'll group instead
input <- input %>%
mutate(n = 1:n()) %>%
group_by(n) %>%
mutate(safe = map_lgl(d, report_safe))
sum(input$safe)
##### Part 2 #####
values_safe <- function(vals) {
difs <- diff(vals)
if( all(difs < 0) | all(difs > 0) ) {
absdifs <- abs(difs)
if( all(absdifs > 0) & all(absdifs < 4) ) {
return(TRUE)
}
}
return(FALSE)
}
report_safe_tol <- function(report) {
vals <- as.numeric(str_split(report, " ")[[1]])
if(values_safe(vals)) {
return(TRUE)
}
for(i in 1:length(vals)) {
vals_tol <- vals[-i]
if(values_safe(vals_tol)) {
return(TRUE)
}
}
return(FALSE)
}
input <- input %>%
group_by(n) %>%
mutate(safe_tol = map_lgl(d, report_safe_tol))
sum(input$safe_tol)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment